From f75ef396465bf80df5fb1bd55b205fc3334c6efb Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:20:38 +0100 Subject: [PATCH 01/40] test(backup): prevent disposable database volume leaks --- docker/scripts/test-backup-restore.sh | 1 + skills/backup-restore/SKILL.md | 24 ++++++++++++++++++++++++ todo.md | 2 +- 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 skills/backup-restore/SKILL.md diff --git a/docker/scripts/test-backup-restore.sh b/docker/scripts/test-backup-restore.sh index d6899ed..715ebbd 100755 --- a/docker/scripts/test-backup-restore.sh +++ b/docker/scripts/test-backup-restore.sh @@ -92,6 +92,7 @@ docker network create "$NETWORK_NAME" >/dev/null docker run -d \ --name "$CONTAINER_NAME" \ --network "$NETWORK_NAME" \ + --tmpfs /var/lib/postgresql/data \ -e POSTGRES_DB="$TEST_DB" \ -e POSTGRES_USER="$TEST_USER" \ -e POSTGRES_PASSWORD_FILE=/tmp/test-db-password \ diff --git a/skills/backup-restore/SKILL.md b/skills/backup-restore/SKILL.md new file mode 100644 index 0000000..37507b1 --- /dev/null +++ b/skills/backup-restore/SKILL.md @@ -0,0 +1,24 @@ +--- +name: backup-restore +description: Validate Heimdall PostgreSQL and protected-volume backups using isolated Compose projects and the production backup/restore scripts. +--- + +# Heimdall backup and restore + +Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/restore*.sh`, the backup Compose, or the disaster-recovery runbook. + +## Project-specific behavior + +- PostgreSQL backups use `docker/scripts/backup.sh` and restores use `restore.sh`. Supply credentials through a generated `POSTGRES_PASSWORD_FILE` or a generated environment file; never reuse `docker/.env`, production secrets, or live volumes. +- `backup-protected-data.sh` archives the Central data volume, including local objects and `dp-keys`. Restore with `restore-protected-data.sh` only while Central is stopped. The script overlays files and deliberately keeps unrelated target files. +- PostgreSQL and protected-volume archives are separate snapshots. The application does not coordinate them into one atomic point in time. +- `test-backup-restore.sh` uses a named isolated network, `tmpfs` for its disposable PostgreSQL data directory, and a temporary host directory. Its cleanup must leave no container, network, or anonymous volume. + +## Acceptance + +1. Read `docker/backup/README.md` and `docker/scripts/test-backup-restore.sh` before changing the flow. +2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions. +3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions. +4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO. +5. Tear down only the disposable project with `docker compose -p down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files. +6. Keep S3 round trips, real-volume production recovery, and production RPO/RTO open until validated on their actual service and data. diff --git a/todo.md b/todo.md index 6ccda66..23a6363 100644 --- a/todo.md +++ b/todo.md @@ -39,7 +39,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. - [ ] **Accès caméra #141** La PR #65 ajoute les scénarios API de grant caméra direct, refus cross-camera, suppression logique et restrictions des routes groupes, ainsi que les tests du filtre d’affectations et des hubs après suppression logique ; sa CI est passée. La PR #88 ajoute le remplacement UI atomique, le chargement complet paginé, la protection du brouillon, et la révocation individuelle des accès excédant la limite de 500. La PR #100 ajoute un gate CI strict (>80 % de lignes par classe ciblée) et étend les tests Application, Infrastructure et Web. Le run PR #319 a mesuré : `CameraAccessService` 100 %, `ResourceAccess` 88,46 %, `ResourceAccessFilter` 82,54 %, `UserCameraAccessController` 83,33 % ; handlers/queries/mapping Application de 90 % à 100 %. Restent la validation produit des accès directs/groupes (#133/#134). - [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel. -- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts de sauvegarde/restauration lisent `POSTGRES_PASSWORD_FILE` (Docker secrets); le test PostgreSQL utilise maintenant `backup.sh` pour créer l’archive et `restore.sh` pour la restaurer avec ce secret fichier. Le run local du test isolé a passé 11/11 scénarios; le run PR #388 a passé les tests/builds, les scans serveur/Agent et `CI policy`. `backup.sh` renvoie aussi maintenant un code de succès pour une sauvegarde locale sans S3. L’archive/restauration des objets + `dp-keys` est intégrée à `scripts/ci/verify.sh`; le runbook documente l'installation générée, les noms de volumes, et le test isolé sans exiger un Central démarré. Restent une restauration d'un volume Docker réel, un aller-retour S3 et les mesures RPO/RTO en production. +- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Restent l’aller-retour S3 et les mesures RPO/RTO sur installation/données réelles. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. ## P2 — fonctionnalités et exploitation -- 2.54.1 From 7a98ee8fd3799b433954d259c6d92ac7248b4d6a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:09:11 +0100 Subject: [PATCH 02/40] ci(renovate): preflight Gitea bot authentication --- .gitea/workflows/renovate.yml | 11 ++++- docs/gitea-builds.md | 2 +- scripts/ci/renovate-preflight.mjs | 60 ++++++++++++++++++++++++++ scripts/ci/renovate-preflight.test.mjs | 36 ++++++++++++++++ skills/renovate-automation/SKILL.md | 15 +++++++ todo.md | 5 +-- 6 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 scripts/ci/renovate-preflight.mjs create mode 100644 scripts/ci/renovate-preflight.test.mjs create mode 100644 skills/renovate-automation/SKILL.md diff --git a/.gitea/workflows/renovate.yml b/.gitea/workflows/renovate.yml index eb957b8..1940e95 100644 --- a/.gitea/workflows/renovate.yml +++ b/.gitea/workflows/renovate.yml @@ -16,8 +16,15 @@ jobs: RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }} RENOVATE_ONBOARDING: 'false' steps: + - name: Checkout Renovate preflight + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 1 + persist-credentials: false + - name: Check Renovate credentials against Gitea + run: | + node --test scripts/ci/renovate-preflight.test.mjs + node scripts/ci/renovate-preflight.mjs - name: Create dependency pull requests run: | - test -n "$RENOVATE_TOKEN" - test -n "$RENOVATE_ENDPOINT" renovate arnaud.dartois/Heimdall diff --git a/docs/gitea-builds.md b/docs/gitea-builds.md index fbc24f8..7fc1c77 100644 --- a/docs/gitea-builds.md +++ b/docs/gitea-builds.md @@ -8,7 +8,7 @@ Les jobs exigent `runs-on: [ubuntu-latest, build-agent]`. Déclarer `build-agent Chaque runner lit sa configuration au démarrage. Ne pas rediriger `sources.tordais.cc` vers `host-gateway` dans `container.options` : cela a empêché les checkouts. Le workflow ne publie pas de rapports comme artefacts distants : les fichiers `artifacts/` sont utilisés dans le job (par exemple pour le seuil de couverture), puis disparaissent avec celui-ci. Le run historique #442 a signalé `CreateArtifact: EHOSTUNREACH`; aucun job courant ne dépend du service artefacts pour réussir. -Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_ENDPOINT` et échoue immédiatement si elle est absente. Renseigner l’URL API de la forge sans coder son domaine dans le dépôt. +Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Avant de démarrer Renovate, il vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API. `scripts/ci/cleanup-docker.sh` journalise l'espace et élimine avant/après les builds les anciennes images Heimdall, les volumes Trivy abandonnés, les couches de build inutilisées depuis plus de 30 minutes et les images pendantes. Il ne purge pas les volumes, réseaux ou images nommées des autres projets. Le run #194 sur `runner-odin` a récupéré 95,89 Go avant build et 7,703 Go après job ; les 1 965 tests, deux images et scans ont réussi. diff --git a/scripts/ci/renovate-preflight.mjs b/scripts/ci/renovate-preflight.mjs new file mode 100644 index 0000000..28fd2ed --- /dev/null +++ b/scripts/ci/renovate-preflight.mjs @@ -0,0 +1,60 @@ +import { pathToFileURL } from 'node:url'; + +const endpoint = process.env.RENOVATE_ENDPOINT; +const token = process.env.RENOVATE_TOKEN; +const repository = 'arnaud.dartois/Heimdall'; + +export function validateEndpoint(value) { + let parsed; + try { + parsed = new URL(value); + } catch { + throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.'); + } + + if (parsed.protocol !== 'https:' || parsed.username || parsed.password || + parsed.search || parsed.hash || !parsed.pathname.replace(/\/$/, '').endsWith('/api/v1')) { + throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.'); + } + + return parsed.href.replace(/\/$/, ''); +} + +export async function checkGiteaAccess(apiEndpoint, accessToken, fetchImpl = fetch) { + const root = `${validateEndpoint(apiEndpoint)}/`; + const urls = [new URL('user', root), new URL(`repos/${repository}`, root)]; + + for (const url of urls) { + let response; + try { + response = await fetchImpl(url, { + headers: { Authorization: `token ${accessToken}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }); + } catch (error) { + throw new Error(`Gitea API preflight could not connect (${error?.name ?? 'network error'}).`); + } + + if (!response.ok) { + const detail = response.status === 401 || response.status === 403 + ? 'Check that RENOVATE_TOKEN is active and has repository read and write access.' + : 'Check GITEA_API_ENDPOINT and the Gitea API availability.'; + throw new Error(`Gitea API preflight failed with HTTP ${response.status}. ${detail}`); + } + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + if (!token) { + console.error('RENOVATE_TOKEN is missing. Configure it as a Gitea Actions secret.'); + process.exitCode = 1; + } else { + try { + await checkGiteaAccess(endpoint, token); + console.log('Renovate token authenticated with Gitea and can read the target repository.'); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } + } +} diff --git a/scripts/ci/renovate-preflight.test.mjs b/scripts/ci/renovate-preflight.test.mjs new file mode 100644 index 0000000..cf249af --- /dev/null +++ b/scripts/ci/renovate-preflight.test.mjs @@ -0,0 +1,36 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { checkGiteaAccess, validateEndpoint } from './renovate-preflight.mjs'; + +test('accepts an HTTPS Gitea API endpoint and trims its trailing slash', () => { + assert.equal(validateEndpoint('https://forge.example/api/v1/'), 'https://forge.example/api/v1'); +}); + +test('rejects non-HTTPS, malformed, and non-API endpoints', () => { + for (const value of ['http://forge.example/api/v1', 'https://forge.example/', 'not a URL']) { + assert.throws(() => validateEndpoint(value), /HTTPS URL ending in \/api\/v1/); + } +}); + +test('checks identity and repository reads without exposing the token', async () => { + const calls = []; + await checkGiteaAccess('https://forge.example/api/v1', 'secret-token', async (url, options) => { + calls.push({ url: url.href, authorization: options.headers.Authorization }); + return { ok: true, status: 200 }; + }); + assert.deepEqual(calls.map(call => new URL(call.url).pathname), [ + '/api/v1/user', '/api/v1/repos/arnaud.dartois/Heimdall', + ]); + assert.ok(calls.every(call => call.authorization === 'token secret-token')); +}); + +test('reports authentication status without printing response details or credentials', async () => { + await assert.rejects( + checkGiteaAccess('https://forge.example/api/v1', 'secret-token', async () => ({ + ok: false, status: 403, + })), + error => error.message.includes('HTTP 403') && + error.message.includes('repository read and write access') && + !error.message.includes('secret-token'), + ); +}); diff --git a/skills/renovate-automation/SKILL.md b/skills/renovate-automation/SKILL.md new file mode 100644 index 0000000..3a3f21b --- /dev/null +++ b/skills/renovate-automation/SKILL.md @@ -0,0 +1,15 @@ +--- +name: renovate-automation +description: Diagnose and maintain Renovate dependency updates through Gitea Actions without exposing bot credentials. +--- + +# Heimdall Renovate workflow + +Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependency-update failures. + +- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `GITEA_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files. +- The endpoint must be the HTTPS Gitea API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values. +- HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR. +- Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials. +- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Remove that exact project and confirm it leaves no containers or volumes; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored. +- For operational changes, update the P0 Renovate status in `todo.md` with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence. diff --git a/todo.md b/todo.md index 23a6363..ef4d94e 100644 --- a/todo.md +++ b/todo.md @@ -10,11 +10,10 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] Retirer `build-agent` de `runner-aaja` et le réserver aux runners de build autorisés. Le run PR #193 lui avait été affecté puis annulé ; le propriétaire a confirmé le retrait du label le 24 octobre 2026. Le run PR #194 s'exécute sur `runner-odin`. - [x] Valider le nettoyage Docker borné avant/après CI sur `runner-odin`. Les runs PR #189 et #191 avaient échoué pendant `dotnet build` avec `No space left on device`. Le run PR #194 a récupéré 95,89 Go avant build, ramené l'utilisation du disque de 97 % à 17 %, puis libéré 7,703 Go après job ; compilation, 1 965 tests, images et sécurité sont passés. Le script retire les anciennes images Heimdall, les volumes Trivy orphelins, les couches de build inutilisées de plus de 30 minutes et les images pendantes, sans purger les volumes ni les images nommées des autres projets. - [x] Vérifier en exécution la publication Docker Hub des images serveur `eltruncho/heimdall` et agent `eltruncho/heimdall-agent` après merge sur `main`, avec les tags `latest` et `sha-`. Les runs main #227 (`e4dc00ca`) et #243 (`d59b546b`, 24 octobre 2026) ont réussi les deux builds/scans et le job « Publish Docker Hub latest tags » ; ces publications confirment que les secrets utilisés par ce workflow sont opérationnels. -- [ ] Valider la variable `RELEASE_SERVER_URL` et une publication signée de release sur Docker Hub. Les images serveur et Agent sont fixées à `eltruncho/heimdall` et `eltruncho/heimdall-agent`; les secrets `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN` sont utilisés par les workflows. La création de `RELEASE_SERVER_URL` a répondu HTTP 201 le 26 octobre 2026, mais sa lecture de confirmation a expiré ; aucun push de release taguée n'a été réalisé. +- [ ] Valider la publication signée de release de bout en bout. Le 4 novembre 2026, l’API Gitea a confirmé que `RELEASE_SERVER_URL` existe et correspond à l’origine de la forge; `.gitea/workflows/build.yml` compare cette valeur à `BUILD_SERVER_URL` avant toute publication. Le parcours restant comprend les secrets du registre Gitea, la clé ECDSA P-256, la reconstruction des archives, les digests et images `eltruncho/heimdall` / `eltruncho/heimdall-agent`, le brouillon avec ses assets, puis installation et rollback Agent. La validation locale des contrats et appels API simulés ne publie rien; aucun tag de release n’a encore exécuté le workflow avec les secrets de publication, donc cette recette réelle reste à faire. - [x] Ne pas publier les rapports CI comme artefacts distants : aucun job actuel ne les consomme après le contrôle de couverture dans `verify`, et l'échec historique `CreateArtifact: EHOSTUNREACH` ne justifie pas de dépendre du service runner. Les fichiers `artifacts/` restent locaux au job pour les tests, les rapports de sécurité et le packaging ; ils ne sont pas téléversés. -- [ ] Diagnostiquer Renovate : les tâches planifiée #372 et manuelle #383 ont échoué. Le jeton courant ne permet pas de lire les secrets d'organisation (HTTP 403, portée `read:organization` absente), donc la présence et le propriétaire de `RENOVATE_TOKEN` restent à confirmer ; les journaux inspectés ne montrent pas d'erreur 401/403 d'authentification Renovate. +- [ ] **Renovate** Le run planifié #401 (2 novembre 2026) échoue dans l’initialisation Renovate avec `Authentication failure`, après que le contrôle de présence du secret a réussi. La vérification des journaux et de l’API ne révèle pas la valeur ni la portée du secret `RENOVATE_TOKEN`; l’API Actions consultée expose `RELEASE_SERVER_URL`, mais pas le secret. Une prévalidation a été ajoutée dans cette branche : vérification HTTPS de `GITEA_API_ENDPOINT`, appel authentifié `/user` et lecture du dépôt cible, avec statut HTTP sans fuite de jeton. Tests Node locaux 4/4; le test Compose jetable est à refaire car le pull de `node:22-alpine` est resté bloqué, sans conteneur ni volume résiduel. Restent à corriger/valider le secret bot à distance et obtenir un run Renovate réussi avec accès d’écriture confirmé. Voir `skills/renovate-automation/SKILL.md`. - [x] Vérifier la protection de `main` : Gitea interdit les pushes directs et les force-pushes, empêche l'override administrateur de merge, et exige `Heimdall Gitea / CI policy (pull_request)`. Le run PR #305 a validé ce job après les tests et les scans ; le run documentaire #309 a réussi avec les builds lourds ignorés. La PR temporaire rouge #98 (run #311) a fait échouer le détecteur et `CI policy`, puis l'API de merge a répondu HTTP 405 « Not all required status checks successful ». La PR de test a été fermée et sa branche supprimée. -- [ ] Valider une release taguée de bout en bout : secrets du registre Gitea, signature ECDSA P-256, archives, digests, brouillon et installation/rollback agent. - [x] Réduire les restaurations répétées : après le restore verrouillé du build, le scan NuGet réutilise les assets avec `security.sh dependencies --no-restore`; l'appel autonome conserve le restore par défaut. Sur le même runner `runner-murin`, la porte NuGet a duré 51 s avant l'optimisation (run main #227) et 36 s sur la PR #71, puis 29 s et 31 s sur `main` après merge (runs #230/#239/#243). La médiane après changement est 31 s, soit 20 s de moins (39 %) que la mesure de référence ; les durées CI restent indicatives, les conditions de cache et de charge n'étant pas contrôlées. ## P1 — parcours caméra, agent et données -- 2.54.1 From 0d5c6576ade4c447966739cd3e099a28a42958ec Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:18:12 +0100 Subject: [PATCH 03/40] feat(pwa): add install help and safe updates --- docs/pwa.md | 12 +- skills/pwa/SKILL.md | 23 ++++ src/Heimdall.Web/wwwroot/app.css | 36 ++++- src/Heimdall.Web/wwwroot/js/pwa-register.js | 138 ++++++++++++++++---- src/Heimdall.Web/wwwroot/service-worker.js | 7 +- tests/Heimdall.E2E.Tests/Pages/PwaTests.cs | 62 +++++++++ todo.md | 4 +- 7 files changed, 245 insertions(+), 37 deletions(-) create mode 100644 skills/pwa/SKILL.md create mode 100644 tests/Heimdall.E2E.Tests/Pages/PwaTests.cs diff --git a/docs/pwa.md b/docs/pwa.md index 46875f9..cd07f3d 100644 --- a/docs/pwa.md +++ b/docs/pwa.md @@ -27,9 +27,9 @@ Les critères d’installation varient selon navigateur ; manifeste et contexte | Rendu | App.razor impose InteractiveServer, prerender désactivé | Conserver en V1 ; écran hors ligne indépendant de Blazor | | Manifeste | `manifest.webmanifest` est lié dans `App.razor` ; nom, langue, couleurs, scope `/` et icône SVG sont définis | Valider l’installation sur les navigateurs ciblés ; ajouter des icônes raster si nécessaire | | Icônes | Favicon existant et icône SVG PWA déclarée `any maskable` | Vérifier le rendu réel ; fournir les variantes raster et Apple touch si requises par les plateformes ciblées | -| Service worker | `service-worker.js` versionne le cache public et ne sert la page hors connexion qu’en échec de navigation GET même origine | Valider le cycle de mise à jour et le rollback sur build publié | +| Service worker | `service-worker.js` versionne le cache public et ne sert la page hors connexion qu’en échec de navigation GET même origine ; une nouvelle version attend désormais l’action de rechargement | Parcours local publié testé par E2E ; valider les appareils et le rollback sur un déploiement | | Hors connexion | `offline.html` est une page statique ; seuls cette page, le manifeste et l’icône sont mis en cache | Vérifier les scénarios réseau sur appareils ; aucune donnée métier ou réponse authentifiée n’est disponible hors ligne | -| Reconnexion | Composant ReconnectModal et module JS existent, sans insertion trouvée dans App/Layouts | Raccorder explicitement et valider sa compatibilité au runtime | +| Reconnexion | L’indicateur Blazor d’erreur de circuit et ses actions de reprise/rechargement sont présents dans `App.razor` | Veille prolongée, changement réseau et reprise de session restent à valider sur appareils | | Web Push | Aucun PushSubscription, PushManager ou configuration VAPID | Construire backend et client | | Notifications | SignalR, email, ntfy et préférences existent | Réutiliser la sélection de destinataires, ajouter un canal navigateur | | Auth | Cookie + JWT + refresh maison | Corriger les défauts SEC-01/02/07/10 de l’audit général | @@ -37,11 +37,11 @@ Les critères d’installation varient selon navigateur ; manifeste et contexte | Layout mobile | MudDrawer responsive, quelques règles CSS mobiles | Auditer chaque écran et dialog sur petit écran | | Langue | `App.razor` indique `lang="fr"` ; le manifeste indique `fr-FR` | Vérifier les contenus localisés par utilisateur lorsque la localisation sera livrée | | HTTPS/proxy | HSTS présent ; redirection conditionnelle ; pas de UseForwardedHeaders observé | Documenter TLS externe et reconnaître uniquement les proxies de confiance | -| Tests | bUnit et Playwright disponibles | Étendre aux scénarios PWA et appareils réels | +| Tests | E2E Playwright vérifie le manifeste, les icônes publiques, le contenu exact du cache et la navigation hors ligne | Installation, mises à jour à deux onglets, rollback, mobile et HTTPS restent à valider sur appareils/déploiement | ### État du socle livré par la PR #64 -Le déploiement actuel suppose que Heimdall est servi à la racine de l’origine (`/`) : le manifeste, le scope, l’enregistrement du worker et ses chemins sont absolus. Un hébergement sous un préfixe (`PathBase`) n’est pas pris en charge par ce socle. Le worker ne met pas en cache le HTML de l’application, les réponses API, les hubs, les médias ou les données privées. Hors connexion, seule la page statique d’information fonctionne ; les interactions Blazor nécessitent une connexion au serveur. L’installation réelle exige une origine HTTPS reconnue (sauf localhost de développement). La validation Android/iOS/desktop, les icônes propres aux plateformes, la reprise mobile et Web Push restent à faire. +Le déploiement actuel suppose que Heimdall est servi à la racine de l’origine (`/`) : le manifeste, le scope, l’enregistrement du worker et ses chemins sont absolus. Un hébergement sous un préfixe (`PathBase`) n’est pas pris en charge. Le worker ne met pas en cache le HTML de l’application, les réponses API, les hubs, les médias ou les données privées. Hors connexion, seule la page statique d’information fonctionne ; les interactions Blazor nécessitent une connexion au serveur. L’aide d’installation utilise `beforeinstallprompt` lorsqu’il est disponible et explique sinon le menu du navigateur, notamment « Sur l’écran d’accueil » sur Safari iOS. Les mises à jour du worker restent en attente jusqu’au choix explicite « Recharger ». L’installation réelle exige une origine HTTPS reconnue (sauf localhost de développement). La validation Android/iOS/desktop, la reprise mobile, le rollback sur déploiement et Web Push restent à faire. Sources locales principales : [App.razor](../src/Heimdall.Web/Components/App.razor), [Program.cs](../src/Heimdall.Web/Program.cs), [MainLayout](../src/Heimdall.Web/Components/Layout/MainLayout.razor), [ReconnectModal](../src/Heimdall.Web/Components/Layout/ReconnectModal.razor), [AuthStateProvider](../src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs), [NotificationService](../src/Heimdall.Infrastructure/Services/NotificationService.cs). @@ -51,7 +51,7 @@ Sources locales principales : [App.razor](../src/Heimdall.Web/Components/App.raz Le manifeste, son lien dans `App.razor`, l’identité stable, la langue et l’icône SVG sont livrés par la PR #64. Le déploiement supporté est à la racine de l’origine (`/`) ; `PathBase` n’est pas pris en charge. Restent à valider l’installation sur les navigateurs cibles, les icônes raster/Apple si nécessaires et les deep links disponibles avant de les proposer comme raccourcis. -L’aide d’installation progressive (événement d’installation quand disponible, instructions propres au navigateur sinon) reste à implémenter. Un navigateur sans installation doit garder une interface utilisable. +L’interface propose l’installation via l’événement natif quand le navigateur le fournit et donne des instructions de menu adaptées au navigateur sinon. Un navigateur sans installation garde une interface utilisable. Les tests E2E valident le manifeste et les ressources d’installation sans authentification ; l’installation effective exige des appareils et une origine HTTPS de déploiement. ### PWA-02 — HTTPS utilisable en auto-hébergement @@ -80,7 +80,7 @@ Ne pas servir systématiquement `offline.html` pour toutes les navigations : une ### PWA-04 — Mise à jour sans casser les circuits -Le cache est versionné et les anciennes versions sont nettoyées. Le worker appelle actuellement `skipWaiting()` puis `clients.claim()`, ce qui active la nouvelle version sans action utilisateur. Ajouter un état « nouvelle version disponible » et une action de rechargement explicite, puis éviter une activation forcée au milieu d’un formulaire ou d’une session live. Gérer les onglets multiples et le déploiement d’une version serveur incompatible avec les assets déjà chargés. La validation doit porter sur le résultat de `dotnet publish`, pas uniquement sur le serveur de développement. +Le cache est versionné et les anciennes versions sont nettoyées à l’activation. Une nouvelle version installée reste en attente ; l’interface annonce sa disponibilité et transmet `ACTIVATE_UPDATE` uniquement après le clic sur « Recharger », puis recharge à `controllerchange`. Cela évite le remplacement forcé au milieu d’un formulaire ou d’une session live. Les E2E vérifient le shell public et la réponse hors ligne ; les onglets multiples et le rollback d’un build publié restent à vérifier sur un navigateur de déploiement. L’URL stable et le nettoyage des caches sont en place. Il reste à établir une procédure opérateur et tester le rollback d’un worker défectueux. Une mise à jour de l’application serveur et une mise à jour du cache navigateur sont deux cycles à coordonner. diff --git a/skills/pwa/SKILL.md b/skills/pwa/SKILL.md new file mode 100644 index 0000000..7db16e1 --- /dev/null +++ b/skills/pwa/SKILL.md @@ -0,0 +1,23 @@ +--- +name: heimdall-pwa +description: Implement and accept Heimdall's root-hosted, online-first Blazor PWA without persisting private application data. +--- + +# Heimdall PWA + +The supported PWA deployment is at the web origin root (`/`). The Blazor app uses Interactive Server, so camera, event, account and administration screens require a live server circuit. Offline mode is an informational page only; never add authenticated HTML, API results, media, credentials or SignalR traffic to CacheStorage or replay mutations offline. + +## Implementation map + +- `src/Heimdall.Web/Components/App.razor` links the web manifest and raster/Apple icons and loads `js/pwa-register.js`. +- `wwwroot/manifest.webmanifest` defines stable root scope, standalone display and PNG/SVG icons. +- `wwwroot/service-worker.js` caches only `/offline.html`, `/manifest.webmanifest` and `/pwa-icon.svg`. It falls back only for failed same-origin GET navigations and excludes API, auth, Blazor, hubs, health, metrics and operational/documentation paths. +- The worker must remain waiting after an update. `pwa-register.js` shows a reload action for a waiting worker; only that action sends `ACTIVATE_UPDATE`, then reloads after `controllerchange`. Do not unconditionally call `skipWaiting()` or `clients.claim()` because this can replace resources during an active form or live session. +- Installation UI is progressive: use `beforeinstallprompt` where the browser provides it; otherwise explain the platform's browser-menu installation steps. Browsers without PWA installation support must keep the site usable. + +## Acceptance + +1. Run `tests/Heimdall.E2E.Tests` with its disposable PostgreSQL fixture and Chromium. Check unauthenticated manifest and icon access, exact public-shell contents, offline navigation fallback, and absence of cached private content. +2. Build the changed source through the disposable Central + PostgreSQL Compose recipe in `skills/compose-disposable-recipe/SKILL.md`; probe `/healthz`, `/manifest.webmanifest`, `/service-worker.js` and the offline page. Use unique project/ports/credentials/volumes and verify teardown. +3. Review `docs/pwa.md` and deployment instructions for HTTPS, root hosting, reverse proxy/WebSocket support, update and rollback behavior. Report physical iOS/Android/desktop installation, HTTPS proxy, and mobile sleep/network testing only when run on those real environments. +4. Keep the PWA backlog open for validations that require real browsers/devices or remote push infrastructure. Do not claim Web Push exists without a tested VAPID backend, subscriptions, revocation and permission-aware delivery. diff --git a/src/Heimdall.Web/wwwroot/app.css b/src/Heimdall.Web/wwwroot/app.css index 27a0770..eb81123 100644 --- a/src/Heimdall.Web/wwwroot/app.css +++ b/src/Heimdall.Web/wwwroot/app.css @@ -894,7 +894,7 @@ html.mud-theme-dark .hmd-code-block { } } -.pwa-update-banner { +.pwa-notice { position: fixed; z-index: 1500; inset-inline: 1rem; @@ -911,7 +911,7 @@ html.mud-theme-dark .hmd-code-block { box-shadow: 0 0.5rem 1.5rem rgba(16, 24, 40, 0.3); } -.pwa-update-banner button { +.pwa-notice button { min-height: 2.5rem; padding: 0.4rem 0.8rem; color: #101828; @@ -921,7 +921,7 @@ html.mud-theme-dark .hmd-code-block { cursor: pointer; } -.pwa-update-banner .pwa-update-dismiss { +.pwa-notice .pwa-notice-dismiss { min-width: 2.5rem; padding: 0.25rem; color: #fff; @@ -930,8 +930,36 @@ html.mud-theme-dark .hmd-code-block { } @media (max-width: 36rem) { - .pwa-update-banner { + .pwa-notice { flex-wrap: wrap; justify-content: flex-start; } } + +.pwa-install-help { + width: min(32rem, calc(100vw - 2rem)); + padding: 1.25rem; + color: #101828; + background: #fff; + border: 0; + border-radius: 0.75rem; + box-shadow: 0 1rem 3rem rgba(16, 24, 40, 0.3); +} + +.pwa-install-help::backdrop { + background: rgba(16, 24, 40, 0.55); +} + +.pwa-install-help h2 { + margin-top: 0; +} + +.pwa-install-help button { + min-height: 2.75rem; + padding: 0.5rem 1rem; + color: #fff; + background: #101828; + border: 0; + border-radius: 0.4rem; + cursor: pointer; +} diff --git a/src/Heimdall.Web/wwwroot/js/pwa-register.js b/src/Heimdall.Web/wwwroot/js/pwa-register.js index c170753..162eb55 100644 --- a/src/Heimdall.Web/wwwroot/js/pwa-register.js +++ b/src/Heimdall.Web/wwwroot/js/pwa-register.js @@ -1,54 +1,144 @@ (() => { if (!("serviceWorker" in navigator) || !window.isSecureContext) return; - let pageIsControlled = Boolean(navigator.serviceWorker.controller); + const isEnglish = document.documentElement.lang.toLowerCase().startsWith("en"); + let installPromptEvent; let updatePromptShown = false; - const showUpdatePrompt = () => { - if (updatePromptShown) return; - updatePromptShown = true; - - const isEnglish = document.documentElement.lang.toLowerCase().startsWith("en"); + const addBanner = ({ className, messageText, actionText, onAction, dismissLabel }) => { const banner = document.createElement("aside"); - banner.className = "pwa-update-banner"; + banner.className = `pwa-notice ${className}`; banner.setAttribute("role", "status"); banner.setAttribute("aria-live", "polite"); const message = document.createElement("span"); - message.textContent = isEnglish - ? "A new version of Heimdall is ready. Reload to apply it." - : "Une nouvelle version de Heimdall est prête. Rechargez pour l’appliquer."; + message.textContent = messageText; - const reload = document.createElement("button"); - reload.type = "button"; - reload.textContent = isEnglish ? "Reload" : "Recharger"; - reload.addEventListener("click", () => window.location.reload(), { once: true }); + const action = document.createElement("button"); + action.type = "button"; + action.textContent = actionText; + action.addEventListener("click", onAction); const dismiss = document.createElement("button"); dismiss.type = "button"; - dismiss.className = "pwa-update-dismiss"; - dismiss.setAttribute("aria-label", isEnglish ? "Dismiss update notice" : "Masquer l’avis de mise à jour"); + dismiss.className = "pwa-notice-dismiss"; + dismiss.setAttribute("aria-label", dismissLabel); dismiss.textContent = "×"; dismiss.addEventListener("click", () => banner.remove(), { once: true }); - banner.append(message, reload, dismiss); + banner.append(message, action, dismiss); document.body.append(banner); + return banner; }; + const showInstallHelp = () => { + const dialog = document.createElement("dialog"); + dialog.className = "pwa-install-help"; + dialog.setAttribute("aria-labelledby", "pwa-install-title"); + + const title = document.createElement("h2"); + title.id = "pwa-install-title"; + title.textContent = isEnglish ? "Install Heimdall" : "Installer Heimdall"; + + const instructions = document.createElement("p"); + const userAgent = navigator.userAgent; + if (/iPad|iPhone|iPod/.test(userAgent)) { + instructions.textContent = isEnglish + ? "In Safari, open the Share menu and choose Add to Home Screen." + : "Dans Safari, ouvrez le menu Partager puis choisissez Sur l’écran d’accueil."; + } else if (/Android/.test(userAgent)) { + instructions.textContent = isEnglish + ? "Open the browser menu and choose Install app or Add to Home screen." + : "Ouvrez le menu du navigateur puis choisissez Installer l’application ou Ajouter à l’écran d’accueil."; + } else { + instructions.textContent = isEnglish + ? "Use your browser’s Install app option in the address bar or browser menu." + : "Utilisez l’option Installer l’application dans la barre d’adresse ou le menu du navigateur."; + } + + const close = document.createElement("button"); + close.type = "button"; + close.textContent = isEnglish ? "Close" : "Fermer"; + close.addEventListener("click", () => dialog.close(), { once: true }); + + dialog.append(title, instructions, close); + document.body.append(dialog); + dialog.addEventListener("close", () => dialog.remove(), { once: true }); + dialog.showModal(); + }; + + const showInstallBanner = () => { + if (document.querySelector(".pwa-install-notice")) return; + if (window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true) return; + addBanner({ + className: "pwa-install-notice", + messageText: isEnglish + ? "Install Heimdall for quick access from your device." + : "Installez Heimdall pour y accéder rapidement depuis votre appareil.", + actionText: isEnglish ? "Install" : "Installer", + dismissLabel: isEnglish ? "Dismiss install notice" : "Masquer l’avis d’installation", + onAction: async () => { + if (!installPromptEvent) { + showInstallHelp(); + return; + } + + installPromptEvent.prompt(); + await installPromptEvent.userChoice; + installPromptEvent = undefined; + document.querySelector(".pwa-install-notice")?.remove(); + } + }); + }; + + const showUpdateBanner = registration => { + if (updatePromptShown) return; + updatePromptShown = true; + + addBanner({ + className: "pwa-update-notice", + messageText: isEnglish + ? "A new version of Heimdall is ready. Reload to apply it." + : "Une nouvelle version de Heimdall est prête. Rechargez pour l’appliquer.", + actionText: isEnglish ? "Reload" : "Recharger", + dismissLabel: isEnglish ? "Dismiss update notice" : "Masquer l’avis de mise à jour", + onAction: () => { + const waitingWorker = registration.waiting; + if (!waitingWorker) { + window.location.reload(); + return; + } + + navigator.serviceWorker.addEventListener("controllerchange", () => window.location.reload(), { once: true }); + waitingWorker.postMessage({ type: "ACTIVATE_UPDATE" }); + } + }); + }; + + window.addEventListener("beforeinstallprompt", event => { + event.preventDefault(); + installPromptEvent = event; + showInstallBanner(); + }); + + window.addEventListener("appinstalled", () => { + installPromptEvent = undefined; + document.querySelector(".pwa-install-notice")?.remove(); + }); + window.addEventListener("load", () => { + showInstallBanner(); navigator.serviceWorker.register("/service-worker.js", { scope: "/" }).then(registration => { - const observeUpdate = worker => { + const showWhenInstalled = worker => { if (!worker) return; worker.addEventListener("statechange", () => { - if (pageIsControlled && worker.state === "installed") showUpdatePrompt(); + if (worker.state === "installed" && registration.active) showUpdateBanner(registration); }); }; - observeUpdate(registration.installing); - registration.addEventListener("updatefound", () => observeUpdate(registration.installing)); - navigator.serviceWorker.addEventListener("controllerchange", () => { - pageIsControlled = true; - }); + if (registration.waiting) showUpdateBanner(registration); + showWhenInstalled(registration.installing); + registration.addEventListener("updatefound", () => showWhenInstalled(registration.installing)); }).catch(() => {}); }, { once: true }); })(); diff --git a/src/Heimdall.Web/wwwroot/service-worker.js b/src/Heimdall.Web/wwwroot/service-worker.js index 97a1065..4299b4f 100644 --- a/src/Heimdall.Web/wwwroot/service-worker.js +++ b/src/Heimdall.Web/wwwroot/service-worker.js @@ -34,10 +34,15 @@ self.addEventListener("install", event => { event.waitUntil( caches.open(CACHE_NAME) .then(cache => cache.addAll(PUBLIC_SHELL)) - .then(() => self.skipWaiting()) ); }); +self.addEventListener("message", event => { + if (event.data?.type === "ACTIVATE_UPDATE") { + self.skipWaiting(); + } +}); + self.addEventListener("activate", event => { event.waitUntil((async () => { const names = await caches.keys(); diff --git a/tests/Heimdall.E2E.Tests/Pages/PwaTests.cs b/tests/Heimdall.E2E.Tests/Pages/PwaTests.cs new file mode 100644 index 0000000..7e384d0 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/PwaTests.cs @@ -0,0 +1,62 @@ +using System.Net; +using System.Text.Json; +using Shouldly; + +namespace Heimdall.E2E.Tests.Pages; + +[Collection("E2E")] +public class PwaTests : E2ETestBase +{ + public PwaTests(TestCommon.PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task Manifest_and_public_shell_are_available_without_authentication() + { + using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + using var manifestResponse = await http.GetAsync("/manifest.webmanifest"); + manifestResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + + using var manifest = JsonDocument.Parse(await manifestResponse.Content.ReadAsStringAsync()); + manifest.RootElement.GetProperty("start_url").GetString().ShouldBe("/"); + manifest.RootElement.GetProperty("scope").GetString().ShouldBe("/"); + manifest.RootElement.GetProperty("display").GetString().ShouldBe("standalone"); + manifest.RootElement.GetProperty("icons").GetArrayLength().ShouldBeGreaterThanOrEqualTo(3); + + foreach (var asset in new[] { "/service-worker.js", "/offline.html", "/pwa-icon.svg", "/pwa-icon-180.png", "/pwa-icon-192.png", "/pwa-icon-512.png" }) + { + using var response = await http.GetAsync(asset); + response.StatusCode.ShouldBe(HttpStatusCode.OK, asset); + } + } + + [Fact] + public async Task Offline_navigation_serves_only_the_public_offline_page() + { + await Page.GotoAsync($"{BaseUrl}/login"); + await Page.EvaluateAsync("async () => await navigator.serviceWorker.ready"); + await Page.GotoAsync($"{BaseUrl}/login"); + await Page.WaitForFunctionAsync("() => !!navigator.serviceWorker.controller"); + + var publicShell = await Page.EvaluateAsync(@"async () => { + const cache = await caches.open('heimdall-public-shell-v1'); + return (await cache.keys()).map(request => new URL(request.url).pathname).sort(); + }"); + publicShell.ShouldBe(new[] { + "/manifest.webmanifest", + "/offline.html", + "/pwa-icon.svg" + }); + + await Page.Context.SetOfflineAsync(true); + try + { + await Page.GotoAsync($"{BaseUrl}/dashboard", new() { WaitUntil = Microsoft.Playwright.WaitUntilState.Commit }); + (await Page.Locator("h1").InnerTextAsync()).ShouldBe("Connexion au serveur impossible"); + (await Page.Locator("body").InnerTextAsync()).ShouldNotContain("dashboard"); + } + finally + { + await Page.Context.SetOfflineAsync(false); + } + } +} diff --git a/todo.md b/todo.md index ef4d94e..913b965 100644 --- a/todo.md +++ b/todo.md @@ -31,7 +31,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), et la validation du changement de provider sur stockage déployé. - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. -- [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; le Compose Central/PostgreSQL/Watchtower a passé la recette jetable, le health check Central et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. +- [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. - [ ] **AGENT-08** Valider reconnexion, remplacement atomique de configuration caméra et ACK persisté sur Agent déployé. - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. @@ -44,7 +44,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. -- [ ] **PWA** PR #64 livre le manifeste, une icône SVG, l'enregistrement du service worker et une page hors connexion statique ; cache public limité à ces trois fichiers, sans mise en cache des données métier. Le fallback offline est exclu des navigations API/auth, hubs, Hangfire, métriques, santé et documentation technique. Le cycle de mise à jour propose un rechargement explicite après installation d'une nouvelle version (installation initiale silencieuse, sans actualisation automatique). Des icônes PNG 180/192/512 px sont maintenant déclarées pour Apple et les installateurs Android, avec tests de dimensions et de présence. Restent les validations appareils/HTTPS, reprise mobile, stratégie de rollback et Web Push par utilisateur/appareil. Ne jamais mettre les données privées en cache. +- [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. - [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. - [ ] **FEAT-03 / UI-02** Évaluer modèles/licences visage et plaques, persister `PersonId`/`VehicleId` et lier les événements ; vérifier historique paginé sans confusion d'identité, conservation et suppression des données biométriques. -- 2.54.1 From 3e13785619216f6268e4444caf56c14ec21b345b Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:17:12 +0100 Subject: [PATCH 04/40] test(groups): verify camera access management UI --- skills/camera-access-groups/SKILL.md | 20 +++++++++ .../Components/Pages/GroupsPageTests.cs | 43 +++++++++++++++++++ todo.md | 2 +- 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 skills/camera-access-groups/SKILL.md diff --git a/skills/camera-access-groups/SKILL.md b/skills/camera-access-groups/SKILL.md new file mode 100644 index 0000000..2a5ac30 --- /dev/null +++ b/skills/camera-access-groups/SKILL.md @@ -0,0 +1,20 @@ +--- +name: camera-access-groups +description: Implement and validate Heimdall user-to-camera grants and group camera access through the administration UI and API. +--- + +# Camera access and groups + +Camera visibility is the union of direct camera grants, site-wide grants, legacy user site assignments, and cameras granted to groups the user belongs to. Keep that union in `CameraAccessService` and `ResourceAccess`; do not reimplement partial scope rules in controllers or UI queries. Site and camera resource checks must continue to run at API/application boundaries, including snapshots, events, hubs, and agent assignment. + +Manage group-camera membership through the authenticated `api/groups/{groupId}/cameras` endpoints. The administration page loads all sites and their cameras with bounded paging, displays site names beside cameras, and adds/removes grants through the API. Treat failed loads and mutations as errors; do not optimistically report success. + +When changing this area, verify: + +- `ResourceAccessTests` for the role/grant matrix, live group membership revocation, and union of direct plus group grants. +- `HttpIsolationTests` and the affected API integration tests for real HTTP authorization outcomes. +- `GroupsPageTests` for site/camera labels and the UI add/remove request sequence. +- PostgreSQL integration tests for persistence or query changes; do not use EF InMemory as relational proof. +- The disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md` for behavior or deployment changes, using a unique project, network, credentials, ports, and volumes. + +Use synthetic camera metadata in automated tests. Physical RTSP, snapshot and reconnect behavior is a separate Agent/camera acceptance and must be reported as unverified unless run against real hardware. diff --git a/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs index 2e71ca3..289a398 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs @@ -123,4 +123,47 @@ public class GroupsPageTests : PageTestBase .ShouldContain(m => m.Contains("supprimé", StringComparison.OrdinalIgnoreCase)); }); } + + [Fact] + public async Task GroupsPage_GererAccesCamera_AfficheSiteEtAccordePuisRetireLaCamera() + { + var siteId = Guid.NewGuid(); + var cameraId = Guid.NewGuid(); + var site = new SiteItem(siteId, "Site Lyon", null, "Europe/Paris", null, true, false, DateTime.UtcNow); + var camera = new CameraItem { Id = cameraId, SiteId = siteId, Name = "Entrée", Status = "Online" }; + Handler.OnGet("api/groups", new PagedData([Group()], 1, 1, 20)); + Handler.OnGet("api/sites", new PagedData([site], 1, 1, 100)); + Handler.OnGet($"api/cameras/by-site/{siteId}", new PagedData([camera], 1, 1, 100)); + Handler.OnGet($"api/groups/{GroupId}/cameras", new PagedData([], 0, 1, 100)); + Handler.On(HttpMethod.Post, $"api/groups/{GroupId}/cameras", System.Net.HttpStatusCode.OK); + Handler.On(HttpMethod.Delete, $"api/groups/{GroupId}/cameras/{cameraId}", System.Net.HttpStatusCode.OK); + LoginAs(); + + var cut = RenderPage(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Opérateurs")); + cut.FindAll("button.mud-icon-button") + .Single(button => button.GetAttribute("aria-label") == "Modifier le groupe").Click(); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Site Lyon"); + cut.Markup.ShouldContain("Entrée"); + }); + var addButton = cut.FindAll("button").Last(button => button.TextContent.Trim() == "Ajouter"); + await cut.InvokeAsync(() => addButton.Click()); + + cut.WaitForAssertion(() => + { + Handler.Requests.ShouldContain(request => request.Method == HttpMethod.Post + && request.RequestUri!.AbsolutePath == $"/api/groups/{GroupId}/cameras"); + cut.Markup.ShouldContain("Entrée"); + cut.Markup.ShouldContain("Site Lyon"); + }); + + var removeButton = cut.FindAll("button.mud-icon-button") + .Last(button => button.GetAttribute("title") == "Retirer l'accès caméra du groupe"); + await cut.InvokeAsync(() => removeButton.Click()); + cut.WaitForAssertion(() => Handler.Requests.ShouldContain(request => request.Method == HttpMethod.Delete + && request.RequestUri!.AbsolutePath == $"/api/groups/{GroupId}/cameras/{cameraId}")); + } } diff --git a/todo.md b/todo.md index 913b965..542db8c 100644 --- a/todo.md +++ b/todo.md @@ -36,7 +36,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. -- [ ] **Accès caméra #141** La PR #65 ajoute les scénarios API de grant caméra direct, refus cross-camera, suppression logique et restrictions des routes groupes, ainsi que les tests du filtre d’affectations et des hubs après suppression logique ; sa CI est passée. La PR #88 ajoute le remplacement UI atomique, le chargement complet paginé, la protection du brouillon, et la révocation individuelle des accès excédant la limite de 500. La PR #100 ajoute un gate CI strict (>80 % de lignes par classe ciblée) et étend les tests Application, Infrastructure et Web. Le run PR #319 a mesuré : `CameraAccessService` 100 %, `ResourceAccess` 88,46 %, `ResourceAccessFilter` 82,54 %, `UserCameraAccessController` 83,33 % ; handlers/queries/mapping Application de 90 % à 100 %. Restent la validation produit des accès directs/groupes (#133/#134). +- [x] **Accès caméra #141** Les PR #65/#88/#100 valident API, remplacement UI atomique, chargement paginé, protection du brouillon et révocation des grants excédentaires (>500). Validation complétée sur la branche de clôture : `ResourceAccessTests` vérifie l’union direct + groupe et la révocation live; `HttpIsolationTests` exerce le pipeline HTTP avec périmètres; un test bUnit `GroupsPage_GererAccesCamera_AfficheSiteEtAccordePuisRetireLaCamera` vérifie l’affichage site/caméra et les appels d’ajout/retrait depuis l’UI. Les tests couvrent les priorités d’accès dans l’interface et la révocation; aucune caméra physique n’est requise pour cette gestion des autorisations. Skill dédiée : `skills/camera-access-groups/SKILL.md`. - [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel. - [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Restent l’aller-retour S3 et les mesures RPO/RTO sur installation/données réelles. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. -- 2.54.1 From fc21daeb60d584930db025c5a0ffb66eb9574583 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:33:49 +0100 Subject: [PATCH 05/40] fix(privacy): bound biometric and plate data inputs --- skills/vision-identity/SKILL.md | 33 +++++++++++++++++++ .../RegisterFace/RegisterFaceCommand.cs | 7 ++-- src/Heimdall.Domain/Entities/LicensePlate.cs | 13 +++++++- src/Heimdall.Domain/Entities/Person.cs | 17 +++++++++- .../Services/PersonService.cs | 4 +++ .../Controllers/PersonsController.cs | 2 ++ .../Persons/RegisterFaceHandlerTests.cs | 31 +++++++++++++++++ .../Entities/BusinessEntityTests.cs | 26 +++++++++++++++ .../Entities/PersonTests.cs | 27 +++++++++++++++ .../PersonServiceTests.cs | 25 ++++++++++++++ todo.md | 2 +- 11 files changed, 181 insertions(+), 6 deletions(-) create mode 100644 skills/vision-identity/SKILL.md diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md new file mode 100644 index 0000000..1f96f68 --- /dev/null +++ b/skills/vision-identity/SKILL.md @@ -0,0 +1,33 @@ +--- +name: vision-identity +description: Extend Heimdall's person, face-embedding, vehicle, and license-plate data paths without logging biometric data or shipping unapproved model weights. +--- + +# Heimdall vision identity data + +## Current project behavior + +- `AnalysisJobPollingService` currently executes only `ObjectDetection`; do not describe the current Agent as performing face recognition or license-plate OCR. +- `KnownFace` is a manually registered vector record, not a face detector or recognition model. Inputs are limited to 4,096 finite float values, copied on construction, and the API body is capped at 256 KiB. Never log or include vector values in audit data. +- `LicensePlate` is a persisted observation record. Its text limit must match the PostgreSQL column (20 characters); confidence must be finite and in `[0,1]`. +- Face embeddings, plate text, and source images are sensitive. Preserve per-person deletion/cascade behavior, keep event camera authorization at API and application boundaries, and do not send frames or embeddings to external services. + +## Model review gate + +Before adding inference, record the exact model artifact URL/version, checksum, training-data terms, model-weight license, code/runtime license, regions/languages represented, preprocessing, hardware/runtime requirements, and an offline installation path. A repository code license alone does not establish the license of its pretrained weights. + +Review findings as of 2026-11-04: + +- [InsightFace model-zoo license notice](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md) says its pretrained models are for non-commercial research; do not ship them for this product without separate permission. +- [FaceONNX model README](https://github.com/FaceONNX/FaceONNX.Models/blob/main/README.md) licenses the library as MIT but links models via Google Drive without specifying a separate model-weight license; treat weights as unresolved. +- [PaddleOCR license page](https://www.paddleocr.ai/v2.10.0/en/index.html) states Apache-2.0 for the project. It does not, by itself, establish rights for a particular license-plate model artifact; verify that artifact's own license and training data. +- [LdDl license-plate-recognition](https://github.com/LdDl/license_plate_recognition) declares Apache-2.0 for the repository and says its pretrained networks were trained on Russian plates. The repository does not separately establish weight rights or accuracy for Heimdall's target regions. + +Do not download or bundle model files until their artifact-level rights and target-region accuracy are reviewed. Keep accuracy claims open until validated on an appropriately licensed, representative dataset and camera conditions. + +## Acceptance + +1. Run Domain, Application, Infrastructure, and Web tests for changed layers; test EF translation/deletion behavior with PostgreSQL when persistence semantics change. +2. For a new model, test model verification/hash rejection, explicit opt-in, CPU fallback, and no outbound frame/embedding requests. Keep the exact artifact out of the repo unless its license and source are approved. +3. Exercise person and vehicle access through the authenticated API/UI, including deletion of the person and the documented retention behavior of linked event history and embeddings. +4. For behavior changes, run the disposable Compose acceptance from `skills/compose-disposable-recipe/SKILL.md`; keep generated data and credentials isolated and remove only that project. diff --git a/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs b/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs index 8565a4e..5cb881a 100644 --- a/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs +++ b/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs @@ -19,9 +19,10 @@ public class RegisterFaceCommandHandler : IRequestHandler> Handle(RegisterFaceCommand request, CancellationToken ct) { - // Validate input before checking existence so empty embeddings return 400, not 404. - if (request.Embedding is null || request.Embedding.Length == 0) - return ServiceResult.Failure("Embedding is required and must not be empty.", 400); + // Bound user-provided biometric vectors before EF serializes them to JSONB. + if (!KnownFace.IsValidEmbedding(request.Embedding)) + return ServiceResult.Failure( + $"Embedding must contain between 1 and {KnownFace.MaxEmbeddingDimensions} finite values.", 400); var person = await _db.Persons .Include(p => p.Faces) diff --git a/src/Heimdall.Domain/Entities/LicensePlate.cs b/src/Heimdall.Domain/Entities/LicensePlate.cs index 064305a..8a79abd 100644 --- a/src/Heimdall.Domain/Entities/LicensePlate.cs +++ b/src/Heimdall.Domain/Entities/LicensePlate.cs @@ -8,6 +8,7 @@ namespace Heimdall.Domain.Entities; /// public class LicensePlate : Entity, IAuditableEntity { + public const int MaxPlateTextLength = 20; public string PlateText { get; private set; } = string.Empty; public Guid? VehicleId { get; private set; } public Guid? PersonId { get; private set; } @@ -24,6 +25,11 @@ public class LicensePlate : Entity, IAuditableEntity public LicensePlate(string plateText, Guid? vehicleId = null, Guid? personId = null, double confidence = 0) : base(Guid.NewGuid()) { + if (string.IsNullOrWhiteSpace(plateText) || plateText.Length > MaxPlateTextLength) + throw new ArgumentException($"Plate text must contain between 1 and {MaxPlateTextLength} characters.", nameof(plateText)); + if (!double.IsFinite(confidence) || confidence is < 0 or > 1) + throw new ArgumentOutOfRangeException(nameof(confidence), "Confidence must be finite and between 0 and 1."); + PlateText = plateText; VehicleId = vehicleId; PersonId = personId; @@ -32,5 +38,10 @@ public class LicensePlate : Entity, IAuditableEntity public void AssignVehicle(Guid vehicleId) => VehicleId = vehicleId; public void AssignPerson(Guid personId) => PersonId = personId; - public void UpdateConfidence(double confidence) => Confidence = confidence; + public void UpdateConfidence(double confidence) + { + if (!double.IsFinite(confidence) || confidence is < 0 or > 1) + throw new ArgumentOutOfRangeException(nameof(confidence), "Confidence must be finite and between 0 and 1."); + Confidence = confidence; + } } diff --git a/src/Heimdall.Domain/Entities/Person.cs b/src/Heimdall.Domain/Entities/Person.cs index e16640c..8bd5ee5 100644 --- a/src/Heimdall.Domain/Entities/Person.cs +++ b/src/Heimdall.Domain/Entities/Person.cs @@ -49,6 +49,8 @@ public class Person : Entity, IAuditableEntity /// public class KnownFace : Entity { + public const int MaxEmbeddingDimensions = 4096; + public Guid PersonId { get; private set; } public string? ThumbnailUrl { get; private set; } public float[] Embedding { get; private set; } = []; @@ -62,9 +64,22 @@ public class KnownFace : Entity public KnownFace(Guid personId, float[] embedding, string? thumbnailUrl = null, string? sourceEventId = null) : base(Guid.NewGuid()) { + if (personId == Guid.Empty) + throw new ArgumentException("Person ID is required.", nameof(personId)); + if (!IsValidEmbedding(embedding)) + throw new ArgumentException($"Embedding must contain between 1 and {MaxEmbeddingDimensions} finite values.", nameof(embedding)); + if (thumbnailUrl?.Length > 2000) + throw new ArgumentException("Thumbnail URL exceeds the maximum length.", nameof(thumbnailUrl)); + if (sourceEventId?.Length > 100) + throw new ArgumentException("Source event ID exceeds the maximum length.", nameof(sourceEventId)); + PersonId = personId; - Embedding = embedding; + Embedding = embedding.ToArray(); ThumbnailUrl = thumbnailUrl; SourceEventId = sourceEventId; } + + public static bool IsValidEmbedding(float[]? embedding) => + embedding is { Length: > 0 and <= MaxEmbeddingDimensions } && + embedding.All(float.IsFinite); } diff --git a/src/Heimdall.Infrastructure/Services/PersonService.cs b/src/Heimdall.Infrastructure/Services/PersonService.cs index 3800115..0196eaa 100644 --- a/src/Heimdall.Infrastructure/Services/PersonService.cs +++ b/src/Heimdall.Infrastructure/Services/PersonService.cs @@ -77,6 +77,10 @@ public sealed class PersonService : IPersonService public async Task> RegisterFaceAsync(RegisterFaceRequest request, CancellationToken ct) { + if (!KnownFace.IsValidEmbedding(request.Embedding)) + return ServiceResult.Failure( + $"Embedding must contain between 1 and {KnownFace.MaxEmbeddingDimensions} finite values.", 400); + await using var db = await _dbFactory.CreateDbContextAsync(ct); var person = await db.Persons.Include(p => p.Faces).FirstOrDefaultAsync(p => p.Id == request.PersonId, ct).ConfigureAwait(false); if (person is null) return ServiceResult.NotFound("Person not found"); diff --git a/src/Heimdall.Web/Controllers/PersonsController.cs b/src/Heimdall.Web/Controllers/PersonsController.cs index 0b26eca..833b79f 100644 --- a/src/Heimdall.Web/Controllers/PersonsController.cs +++ b/src/Heimdall.Web/Controllers/PersonsController.cs @@ -20,6 +20,7 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class PersonsController : ControllerBase { + private const int MaxFaceRegistrationBytes = 256 * 1024; private readonly IMediator _mediator; public PersonsController(IMediator mediator) => _mediator = mediator; @@ -71,6 +72,7 @@ public class PersonsController : ControllerBase [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.PersonWrite)] [HttpPost("{personId:guid}/faces")] + [RequestSizeLimit(MaxFaceRegistrationBytes)] public async Task RegisterFace(Guid personId, [FromBody] RegisterFaceRequest request, CancellationToken ct) { if (!this.TryGetUserId(out var actorId)) return Unauthorized(); diff --git a/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs index 4f47557..15b3ab7 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs @@ -46,6 +46,37 @@ public class RegisterFaceHandlerTests result.StatusCode.ShouldBe(404); } + [Theory] + [InlineData(float.NaN)] + [InlineData(float.PositiveInfinity)] + public async Task Register_face_should_reject_non_finite_embedding_before_database_lookup(float value) + { + var context = Substitute.For(); + var handler = new RegisterFaceCommandHandler(context); + + var result = await handler.Handle( + new RegisterFaceCommand(Guid.NewGuid(), [value]), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + await context.DidNotReceive().SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Register_face_should_reject_embedding_over_limit_before_database_lookup() + { + var context = Substitute.For(); + var handler = new RegisterFaceCommandHandler(context); + + var result = await handler.Handle( + new RegisterFaceCommand(Guid.NewGuid(), new float[KnownFace.MaxEmbeddingDimensions + 1]), + CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + await context.DidNotReceive().SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + [Fact] public async Task Register_face_should_record_audit_log() { diff --git a/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs b/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs index bdbb362..552ea4d 100644 --- a/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs +++ b/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs @@ -112,6 +112,32 @@ public class BusinessEntityTests plate.PersonId.ShouldBe(personId); } + [Theory] + [InlineData(0.0)] + [InlineData(1.0)] + public void LicensePlate_should_accept_confidence_bounds(double confidence) + { + var plate = new LicensePlate("AB-123-CD", confidence: confidence); + + plate.Confidence.ShouldBe(confidence); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(-0.01)] + [InlineData(1.01)] + public void LicensePlate_should_reject_invalid_confidence(double confidence) + { + Should.Throw(() => new LicensePlate("AB-123-CD", confidence: confidence)); + } + + [Fact] + public void LicensePlate_should_reject_text_over_database_limit() + { + Should.Throw(() => new LicensePlate(new string('A', LicensePlate.MaxPlateTextLength + 1))); + } + // ─── CameraEvent — relations enrichies (spec 2.2) ───────────── [Fact] diff --git a/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs b/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs index d1f3368..50d7d38 100644 --- a/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs +++ b/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs @@ -91,4 +91,31 @@ public class KnownFaceTests face.ThumbnailUrl.ShouldBeNull(); face.SourceEventId.ShouldBeNull(); } + + [Fact] + public void Create_knownface_should_copy_embedding_to_prevent_mutation() + { + var input = new[] { 0.1f, 0.2f }; + var face = new KnownFace(Guid.NewGuid(), input); + + input[0] = 0.9f; + + face.Embedding[0].ShouldBe(0.1f); + } + + [Theory] + [InlineData(float.NaN)] + [InlineData(float.PositiveInfinity)] + public void Create_knownface_should_reject_non_finite_values(float invalidValue) + { + Should.Throw(() => new KnownFace(Guid.NewGuid(), [invalidValue])); + } + + [Fact] + public void Create_knownface_should_reject_embedding_over_limit() + { + var embedding = new float[KnownFace.MaxEmbeddingDimensions + 1]; + + Should.Throw(() => new KnownFace(Guid.NewGuid(), embedding)); + } } diff --git a/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs index 9d6b146..49b4fcb 100644 --- a/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs @@ -136,6 +136,31 @@ public class PersonServiceTests : IDisposable result.Data[2].DisplayName.ShouldBe("Charlie"); } + [Fact] + public async Task RegisterFaceAsync_RejectsOversizedEmbedding() + { + var service = new PersonService(_dbFactory, _logger); + + var result = await service.RegisterFaceAsync( + new RegisterFaceRequest(Guid.NewGuid(), new float[KnownFace.MaxEmbeddingDimensions + 1]), + CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + } + + [Fact] + public async Task RegisterFaceAsync_RejectsNonFiniteEmbedding() + { + var service = new PersonService(_dbFactory, _logger); + + var result = await service.RegisterFaceAsync( + new RegisterFaceRequest(Guid.NewGuid(), [0.1f, float.NaN]), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + } + [Fact] public async Task UpdateAsync_ExistingPerson_UpdatesFields() { diff --git a/todo.md b/todo.md index 542db8c..6284530 100644 --- a/todo.md +++ b/todo.md @@ -47,7 +47,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. - [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. -- [ ] **FEAT-03 / UI-02** Évaluer modèles/licences visage et plaques, persister `PersonId`/`VehicleId` et lier les événements ; vérifier historique paginé sans confusion d'identité, conservation et suppression des données biométriques. +- [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. - [ ] **GPU #77** Les Compose CPU n'exigent plus NVIDIA et n'annoncent plus un `ORT_PROVIDER=CUDA` ignoré. Des overlays optionnels exposent NVIDIA/AMD/Intel à l'inventaire; l'inférence ONNX de l'image Agent reste CPU. Restent une image/runtime GPU, la détection du fournisseur réellement attaché à la session, et les validations GPU réel + fallback CPU. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. -- 2.54.1 From 5bee43e9204e4404e6535da09a5fd570c5031d9c Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:37:26 +0100 Subject: [PATCH 06/40] ci(release): add offline publishing acceptance --- scripts/ci/accept-release-offline.py | 233 +++++++++++++++++++++++++++ skills/release-automation/SKILL.md | 22 +++ todo.md | 2 +- 3 files changed, 256 insertions(+), 1 deletion(-) create mode 100755 scripts/ci/accept-release-offline.py create mode 100644 skills/release-automation/SKILL.md diff --git a/scripts/ci/accept-release-offline.py b/scripts/ci/accept-release-offline.py new file mode 100755 index 0000000..7acb57c --- /dev/null +++ b/scripts/ci/accept-release-offline.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +"""Offline acceptance for package.sh and publish.sh using synthetic credentials and API doubles.""" +import base64 +import email +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import ssl +import subprocess +import sys +import tempfile +import threading +from email import policy +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlsplit + +ROOT = Path(__file__).resolve().parents[2] +REPOSITORY = 'arnaud.dartois/Heimdall' +TAG = 'v1.2.3' +DOCKER_TOKEN = 'offline-docker-token-not-valid' +RELEASE_TOKEN = 'offline-gitea-token-not-valid' +SERVER_DIGEST = 'sha256:' + '1' * 64 +AGENT_DIGEST = 'sha256:' + '2' * 64 + + +def run(command, *, cwd, env, label): + result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True) + if result.returncode: + output = (result.stdout + result.stderr).replace(DOCKER_TOKEN, '[redacted]').replace(RELEASE_TOKEN, '[redacted]') + raise RuntimeError(f'{label} failed ({result.returncode}):\n{output[-12000:]}') + return result.stdout + + +def main(): + artifacts_dir = ROOT / 'artifacts' + if artifacts_dir.exists(): + raise RuntimeError('Refusing to overwrite or remove an existing artifacts/ directory; run from a clean worktree.') + with tempfile.TemporaryDirectory(prefix='heimdall-release-offline-') as temp_name: + temp = Path(temp_name) + cert = temp / 'localhost.pem' + private_cert_key = temp / 'localhost-key.pem' + release_key = temp / 'release-key.pem' + fakebin = temp / 'bin' + fakebin.mkdir() + docker_log = temp / 'docker-commands.jsonl' + release_state = {'draft': None, 'assets': {}, 'authorized': 0} + + subprocess.run([ + 'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-sha256', '-days', '1', '-nodes', + '-keyout', str(private_cert_key), '-out', str(cert), '-subj', '/CN=127.0.0.1', + '-addext', 'subjectAltName=IP:127.0.0.1', + ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(['openssl', 'ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', str(release_key)], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + signing_key_b64 = base64.b64encode(release_key.read_bytes()).decode('ascii') + + docker_stub = r'''#!/usr/bin/env python3 +import json, os, sys +args = sys.argv[1:] +log = os.environ['OFFLINE_DOCKER_LOG'] +with open(log, 'a') as f: f.write(json.dumps(args) + '\n') +if args[:1] == ['build']: + target = args[args.index('-t') + 1] + sys.exit(0) +if args[:2] == ['login', 'docker.io']: + if sys.stdin.read().strip() != os.environ['DOCKERHUB_TOKEN'] or os.environ.get('DOCKERHUB_USERNAME') != 'offline-user': + sys.exit(11) + sys.exit(0) +if args[:2] == ['manifest', 'inspect']: + sys.exit(1) # Simulate absent remote tags; never call a registry. +if args[:1] == ['tag']: + sys.exit(0) +if args[:1] == ['push']: + sys.exit(0) # Simulated push only; no registry client exists in this stub. +if args[:2] == ['image', 'inspect']: + image = args[2].split(':', 1)[0] + digest = 'sha256:' + ('2' if image.endswith('heimdall-agent') else '1') * 64 + print(image + '@' + digest) + sys.exit(0) +sys.exit(12) +''' + docker_path = fakebin / 'docker' + docker_path.write_text(docker_stub) + docker_path.chmod(0o700) + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args): + return + + def _authorized(self): + ok = self.headers.get('Authorization') == 'token ' + RELEASE_TOKEN + if ok: + release_state['authorized'] += 1 + return ok + + def _json(self, status, value): + payload = json.dumps(value).encode() + self.send_response(status) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def do_GET(self): + if not self._authorized(): + self._json(401, {}) + return + path = urlsplit(self.path).path + if path.endswith('/releases/tags/' + TAG): + self._json(404, {'message': 'not found'}) + elif path.endswith('/releases/7301/assets'): + self._json(200, []) + else: + self._json(404, {'message': 'unexpected request'}) + + def do_POST(self): + if not self._authorized(): + self._json(401, {}) + return + path = urlsplit(self.path).path + body = self.rfile.read(int(self.headers.get('Content-Length', '0'))) + if path.endswith('/releases'): + release = json.loads(body) + assert release['tag_name'] == TAG + assert release['draft'] is True + assert release['target_commitish'] == subprocess.check_output( + ['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip() + release_state['draft'] = release + self._json(201, {'id': 7301, 'draft': True, + 'html_url': 'https://gitea.test/releases/7301'}) + return + if path.endswith('/releases/7301/assets'): + content_type = self.headers.get('Content-Type') + message = email.message_from_bytes( + b'Content-Type: ' + content_type.encode() + b'\r\nMIME-Version: 1.0\r\n\r\n' + body, + policy=policy.default, + ) + parts = list(message.iter_parts()) + assert len(parts) == 1 + filename = parts[0].get_filename() + assert filename and filename not in release_state['assets'] + release_state['assets'][filename] = parts[0].get_payload(decode=True) + self._json(201, {'id': 8000 + len(release_state['assets']), 'name': filename}) + return + self._json(404, {'message': 'unexpected request'}) + + server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(cert, private_cert_key) + server.socket = context.wrap_socket(server.socket, server_side=True) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + + try: + origin = f'https://127.0.0.1:{server.server_port}' + env = os.environ.copy() + env.update({ + 'PATH': str(fakebin) + os.pathsep + os.environ['PATH'], + 'SSL_CERT_FILE': str(cert), + 'NO_PROXY': '127.0.0.1,localhost', + 'no_proxy': '127.0.0.1,localhost', + 'BUILD_REF': 'refs/tags/' + TAG, + 'BUILD_REPOSITORY': REPOSITORY, + 'BUILD_RUN_ID': 'offline-acceptance', + 'BUILD_SERVER_URL': origin, + 'EXPECTED_BUILD_SERVER_URL': origin, + 'DOCKERHUB_USERNAME': 'offline-user', + 'DOCKERHUB_TOKEN': DOCKER_TOKEN, + 'RELEASE_TOKEN': RELEASE_TOKEN, + 'RELEASE_SIGNING_KEY_B64': signing_key_b64, + 'OFFLINE_DOCKER_LOG': str(docker_log), + }) + run(['bash', 'scripts/ci/package.sh'], cwd=ROOT, env=env, label='package.sh') + run(['bash', 'scripts/ci/publish.sh'], cwd=ROOT, env=env, label='publish.sh') + + packages = ROOT / 'artifacts/packages' + public_key = temp / 'release-public.pem' + public_key.write_bytes(release_state['assets']['agent-release-public.pem']) + manifest_bytes = release_state['assets']['agent-update-manifest.json'] + signature = temp / 'manifest.sig' + signature.write_bytes(release_state['assets']['agent-update-manifest.sig']) + manifest = json.loads(manifest_bytes) + assert manifest['version'] == TAG + assert manifest['containerImage'] == 'eltruncho/heimdall-agent' + assert manifest['containerImageDigest'] == AGENT_DIGEST + provenance = json.loads(release_state['assets']['provenance.json']) + commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip() + assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/' + TAG + agent_image = json.loads(release_state['assets']['agent-image.json']) + assert agent_image == {'digest': AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent'} + for platform, digest in manifest['assets'].items(): + archive = f'heimdall-agent-{platform}-{TAG.removeprefix("v")}.tar.gz' + assert hashlib.sha256(release_state['assets'][archive]).hexdigest() == digest + subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(public_key), + '-signature', str(signature), str(packages / 'agent-update-manifest.json')], + check=True, stdout=subprocess.DEVNULL) + + checksums = release_state['assets']['SHA256SUMS'].decode().splitlines() + for line in checksums: + digest, filename = line.split(maxsplit=1) + filename = filename.lstrip('* ') + assert filename in release_state['assets'], f'missing checksum asset {filename}' + assert hashlib.sha256(release_state['assets'][filename]).hexdigest() == digest, filename + image_digests = release_state['assets']['image-digests.txt'].decode().splitlines() + assert len(image_digests) == 4 + assert sum(AGENT_DIGEST in item for item in image_digests) == 2 + docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()] + assert sum(call[:1] == ['build'] for call in docker_calls) == 2 + pushes = {call[1] for call in docker_calls if call[:1] == ['push']} + assert len(pushes) == 4 + assert pushes == { + f'eltruncho/heimdall:sha-{commit}', f'eltruncho/heimdall:1.2.3', + f'eltruncho/heimdall-agent:sha-{commit}', f'eltruncho/heimdall-agent:1.2.3', + } + assert sum(call[:1] == ['login'] for call in docker_calls) == 1 + assert release_state['draft']['draft'] is True + assert len(release_state['assets']) >= 9 + assert release_state['authorized'] >= 7 + print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} draft assets, checksums, image digests, and four simulated pushes.') + print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.') + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + if artifacts_dir.exists(): + shutil.rmtree(artifacts_dir) + + +if __name__ == '__main__': + main() diff --git a/skills/release-automation/SKILL.md b/skills/release-automation/SKILL.md new file mode 100644 index 0000000..67760df --- /dev/null +++ b/skills/release-automation/SKILL.md @@ -0,0 +1,22 @@ +--- +name: release-automation +description: Build, sign, verify, and publish Heimdall tagged releases without exposing signing keys or publishing from pull requests. +--- + +# Heimdall tagged release workflow + +Use this skill for changes to `scripts/ci/package.sh`, `publish.sh`, `release-gitea.py`, release signing, Docker image tags, or the Gitea release job. + +## Release invariants + +- A release tag must be `vMAJOR.MINOR.PATCH[-prerelease]`, point to a commit on `main`, and pass the complete `verify` job before publication starts. +- `RELEASE_SERVER_URL` must be the expected HTTPS forge origin and must match `BUILD_SERVER_URL`; the publisher rejects paths, query strings, user info, and host/port mismatches. +- Use a dedicated Gitea `RELEASE_TOKEN`, Docker Hub credentials, and a base64 encoded ECDSA P-256 key only in the tagged release job. Never make them available to PR jobs or print them. +- Do not overwrite published image tags owned by another commit or mutate an already published Gitea release. Releases remain drafts until an operator promotes them. +- The release includes deterministic Web and Agent archives, provenance, checksums, the public key, immutable image digests, and a signed Agent update manifest. + +## Offline end-to-end acceptance + +Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. The acceptance script invokes the real `package.sh` and `publish.sh`, but creates disposable ECDSA P-256 credentials and substitutes both publication boundaries: a local TLS Gitea API double records only draft release/assets, and a fake Docker CLI records tags and simulates registry digests. It verifies archive hashes, manifest signature, checksums, asset uploads, and expected image tags/digests. The fake CLI must never call a registry, and the API server must bind only to loopback, suppress request logging, and reject non-synthetic authorization. + +This simulation proves local packaging/signing/orchestration only. It does not prove the Actions secrets, runner network, Docker Hub/Gitea behavior, native Agent installation, or rollback. Keep the release item open in `todo.md` until a real tagged run and the relevant host validation have succeeded. diff --git a/todo.md b/todo.md index 6284530..c4c72d3 100644 --- a/todo.md +++ b/todo.md @@ -10,7 +10,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] Retirer `build-agent` de `runner-aaja` et le réserver aux runners de build autorisés. Le run PR #193 lui avait été affecté puis annulé ; le propriétaire a confirmé le retrait du label le 24 octobre 2026. Le run PR #194 s'exécute sur `runner-odin`. - [x] Valider le nettoyage Docker borné avant/après CI sur `runner-odin`. Les runs PR #189 et #191 avaient échoué pendant `dotnet build` avec `No space left on device`. Le run PR #194 a récupéré 95,89 Go avant build, ramené l'utilisation du disque de 97 % à 17 %, puis libéré 7,703 Go après job ; compilation, 1 965 tests, images et sécurité sont passés. Le script retire les anciennes images Heimdall, les volumes Trivy orphelins, les couches de build inutilisées de plus de 30 minutes et les images pendantes, sans purger les volumes ni les images nommées des autres projets. - [x] Vérifier en exécution la publication Docker Hub des images serveur `eltruncho/heimdall` et agent `eltruncho/heimdall-agent` après merge sur `main`, avec les tags `latest` et `sha-`. Les runs main #227 (`e4dc00ca`) et #243 (`d59b546b`, 24 octobre 2026) ont réussi les deux builds/scans et le job « Publish Docker Hub latest tags » ; ces publications confirment que les secrets utilisés par ce workflow sont opérationnels. -- [ ] Valider la publication signée de release de bout en bout. Le 4 novembre 2026, l’API Gitea a confirmé que `RELEASE_SERVER_URL` existe et correspond à l’origine de la forge; `.gitea/workflows/build.yml` compare cette valeur à `BUILD_SERVER_URL` avant toute publication. Le parcours restant comprend les secrets du registre Gitea, la clé ECDSA P-256, la reconstruction des archives, les digests et images `eltruncho/heimdall` / `eltruncho/heimdall-agent`, le brouillon avec ses assets, puis installation et rollback Agent. La validation locale des contrats et appels API simulés ne publie rien; aucun tag de release n’a encore exécuté le workflow avec les secrets de publication, donc cette recette réelle reste à faire. +- [ ] Valider la publication signée de release de bout en bout. Le 4 novembre 2026, l’API Gitea a confirmé que `RELEASE_SERVER_URL` existe et correspond à l’origine de la forge; `.gitea/workflows/build.yml` compare cette valeur à `BUILD_SERVER_URL` avant toute publication. Le 4 novembre, `python3 scripts/ci/accept-release-offline.py` a exécuté les vrais `package.sh` et `publish.sh` avec clé ECDSA P-256 synthétique, faux Docker CLI et API Gitea TLS sur loopback : archives Web/Agent construites, signature du manifeste vérifiée, sommes de contrôle, digests, 4 pushes simulés et 9 assets du brouillon vérifiés. Aucun service distant ni Docker réel n’a été contacté. Le parcours restant comprend les secrets du registre Gitea, la clé Actions ECDSA, les images Docker Hub `eltruncho/heimdall` / `eltruncho/heimdall-agent`, un run tagué créant le brouillon, puis installation et rollback Agent sur hôtes réels. Voir `skills/release-automation/SKILL.md`. - [x] Ne pas publier les rapports CI comme artefacts distants : aucun job actuel ne les consomme après le contrôle de couverture dans `verify`, et l'échec historique `CreateArtifact: EHOSTUNREACH` ne justifie pas de dépendre du service runner. Les fichiers `artifacts/` restent locaux au job pour les tests, les rapports de sécurité et le packaging ; ils ne sont pas téléversés. - [ ] **Renovate** Le run planifié #401 (2 novembre 2026) échoue dans l’initialisation Renovate avec `Authentication failure`, après que le contrôle de présence du secret a réussi. La vérification des journaux et de l’API ne révèle pas la valeur ni la portée du secret `RENOVATE_TOKEN`; l’API Actions consultée expose `RELEASE_SERVER_URL`, mais pas le secret. Une prévalidation a été ajoutée dans cette branche : vérification HTTPS de `GITEA_API_ENDPOINT`, appel authentifié `/user` et lecture du dépôt cible, avec statut HTTP sans fuite de jeton. Tests Node locaux 4/4; le test Compose jetable est à refaire car le pull de `node:22-alpine` est resté bloqué, sans conteneur ni volume résiduel. Restent à corriger/valider le secret bot à distance et obtenir un run Renovate réussi avec accès d’écriture confirmé. Voir `skills/renovate-automation/SKILL.md`. - [x] Vérifier la protection de `main` : Gitea interdit les pushes directs et les force-pushes, empêche l'override administrateur de merge, et exige `Heimdall Gitea / CI policy (pull_request)`. Le run PR #305 a validé ce job après les tests et les scans ; le run documentaire #309 a réussi avec les builds lourds ignorés. La PR temporaire rouge #98 (run #311) a fait échouer le détecteur et `CI policy`, puis l'API de merge a répondu HTTP 405 « Not all required status checks successful ». La PR de test a été fermée et sa branche supprimée. -- 2.54.1 From e2d3f1054fbbd454b21f47b05c954368434742f0 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 22:02:35 +0100 Subject: [PATCH 07/40] fix(docker): probe health endpoint with GET --- docker/Dockerfile | 2 +- docker/docker-compose.yml | 2 +- skills/server-healthchecks/SKILL.md | 13 +++++++++++++ todo.md | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 skills/server-healthchecks/SKILL.md diff --git a/docker/Dockerfile b/docker/Dockerfile index 237735e..89b54cf 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -14,5 +14,5 @@ RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata ENV ASPNETCORE_URLS=http://+:8080 COPY --from=build /out/ ./ EXPOSE 8080 -HEALTHCHECK --interval=30s --timeout=5s --start-period=60s CMD wget -q --spider http://localhost:8080/healthz || exit 1 +HEALTHCHECK --interval=30s --timeout=5s --start-period=60s CMD wget -q -O /dev/null http://localhost:8080/healthz || exit 1 ENTRYPOINT ["dotnet", "Heimdall.Web.dll"] diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index a575089..8a16920 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -46,7 +46,7 @@ services: postgresql: condition: service_healthy healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://localhost:8080/healthz"] interval: 30s timeout: 10s retries: 3 diff --git a/skills/server-healthchecks/SKILL.md b/skills/server-healthchecks/SKILL.md new file mode 100644 index 0000000..6e1cdff --- /dev/null +++ b/skills/server-healthchecks/SKILL.md @@ -0,0 +1,13 @@ +--- +name: server-healthchecks +description: Keep Heimdall container health probes aligned with the HTTP methods accepted by its ASP.NET health endpoints. +--- + +# Heimdall server health checks + +Use this workflow when changing `Dockerfile` health checks, Central Compose health checks, or Web health endpoint routing. + +- The container probes `/healthz` on port 8080. ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy. +- In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD. +- Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required. +- For acceptance, build the Central image from the changed source in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm Compose reports healthy and remove only that project with `down --volumes --remove-orphans`. Verify no labeled containers, volumes, or networks remain. diff --git a/todo.md b/todo.md index c4c72d3..2d099b7 100644 --- a/todo.md +++ b/todo.md @@ -55,7 +55,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers existe, mais aucun producteur WebRTC n'existe avant FEAT-01. Restent la validation de scraping sur un déploiement et l'évolution réelle des mesures. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. -- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Restent la validation des seuils sur déploiement et les pannes à valider sur déploiement réel. +- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Restent la validation des seuils sur déploiement et les pannes à valider sur déploiement réel. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. - [ ] Actualiser les guides après chaque changement d'infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Vérifier une installation depuis la documentation. ## Corrections déjà livrées à préserver -- 2.54.1 From 830f88c5bf85916d1eeab4fc1c054a9c5190fc8f Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:58:57 +0100 Subject: [PATCH 08/40] feat(agent): configure ONNX CUDA provider with CPU fallback --- docs/gpu-runtime.md | 18 +- skills/gpu-inference/SKILL.md | 28 + src/Heimdall.Agent/AgentOptions.cs | 4 + src/Heimdall.Agent/Heimdall.Agent.csproj | 11 +- src/Heimdall.Agent/Program.cs | 4 +- .../Services/FrameAnalyzerService.cs | 46 +- .../OnnxExecutionProviderSelection.cs | 51 + src/Heimdall.Agent/appsettings.json | 3 +- src/Heimdall.Agent/packages.gpu.lock.json | 357 +++++++ .../Heimdall.Agent.Tests.csproj | 7 + .../OnnxExecutionProviderSelectionTests.cs | 77 ++ .../packages.gpu.lock.json | 953 ++++++++++++++++++ todo.md | 2 +- 13 files changed, 1543 insertions(+), 18 deletions(-) create mode 100644 skills/gpu-inference/SKILL.md create mode 100644 src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs create mode 100644 src/Heimdall.Agent/packages.gpu.lock.json create mode 100644 tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs create mode 100644 tests/Heimdall.Agent.Tests/packages.gpu.lock.json diff --git a/docs/gpu-runtime.md b/docs/gpu-runtime.md index f439f99..d03cf7f 100644 --- a/docs/gpu-runtime.md +++ b/docs/gpu-runtime.md @@ -1,8 +1,12 @@ # GPU device access and inference status The default Agent uses `CPUExecutionProvider`. The published Agent image only -contains the CPU ONNX Runtime package. GPU detection and inventory report host -hardware; they do not mean that frame inference is running on that hardware. +contains the CPU ONNX Runtime package. `Agent__InferenceExecutionProvider` +accepts `CPU` (the default) or `CUDA`; the current published image does not +include the CUDA provider or its CUDA/cuDNN runtime libraries. A CUDA request in +that image is logged and falls back to CPU. GPU detection and inventory report +host hardware; they do not mean that frame inference is running on that +hardware. The production Agent Compose is generated in Central's UI. Save that file as `docker-compose.yml` on the camera host. To expose hardware for inventory, @@ -34,6 +38,10 @@ the host group IDs that can access `/dev/dri`. The NVIDIA option requires the NVIDIA Container Toolkit and Docker Compose GPU device reservations. These overlays only expose devices for Agent inventory. They do not enable -GPU-accelerated ONNX inference. Enabling that requires a GPU-specific runtime -image, selecting and reporting the provider actually attached to the ONNX -session, and validation on real supported hardware with a CPU fallback. +GPU-accelerated ONNX inference. The Agent project has an opt-in GPU package +restore/build variant (`-p:HeimdallOnnxRuntime=GPU`) for provider/fallback +development, but no GPU runtime image is published or selected by the install +UI yet. Actual GPU inference still requires a compatible CUDA/cuDNN runtime, +host driver access, image publication and installer selection, then validation +on real supported hardware. CPU fallback is covered by local tests; hardware +execution is not. diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md new file mode 100644 index 0000000..471f650 --- /dev/null +++ b/skills/gpu-inference/SKILL.md @@ -0,0 +1,28 @@ +--- +name: heimdall-gpu-inference +description: Build and verify Agent ONNX Runtime provider selection, CPU fallback, and GPU package variants in Heimdall. +--- + +# Heimdall Agent ONNX inference + +Use this skill when changing ONNX Runtime packages, execution provider configuration, Agent inference startup, or GPU deployment support. + +## Project-specific workflow + +- The default Agent build and published `docker/Dockerfile.agent` remain CPU-only. Do not add NVIDIA runtime/device requirements to the default Agent Compose files. +- Configure provider choice through `Agent:InferenceExecutionProvider` (environment variable `Agent__InferenceExecutionProvider`). `CPU` is the default. `CUDA` is optional and valid only in a runtime containing the official ONNX Runtime GPU package plus compatible CUDA/cuDNN native libraries and host driver access. +- Keep the CPU and GPU NuGet dependency graphs in their separate lock files. Restore each variant explicitly and in locked mode after changing dependencies: + + ```sh + dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode + dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode + ``` + +- The Agent detects registered providers before creating a session. It reports the provider configured on the resulting session. If CUDA is requested but unavailable or session construction fails, log the reason without sensitive payloads and construct a CPU session. Keep provider selection isolated behind `OnnxExecutionProviderSelection` so the fallback can be tested without hardware. +- Add tests for CPU-only selection, successful CUDA selection, missing CUDA provider, and CUDA session initialization failure. Also exercise the repository YOLO fixture with the CPU provider so package changes preserve real inference. +- Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output. +- Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution. + +## Current limitation + +The codebase contains CPU Agent image publication only. Selecting CUDA in that image must fall back to CPU; do not describe inventory overlays as GPU inference. A GPU image/runtime, publication and installer/UI selection, and hardware acceptance need separate implementation and evidence. diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index 3bcdf59..eda76cf 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -95,6 +95,10 @@ public sealed class AgentOptions /// public AnalysisMode AnalysisMode { get; init; } = AnalysisMode.Local; + /// ONNX execution provider. CPU is the default; CUDA requires a compatible NVIDIA runtime built with the GPU package. + [RegularExpression("^(CPU|CUDA)$")] + public string InferenceExecutionProvider { get; init; } = "CPU"; + /// /// URL of the remote analysis broker (required when AnalysisMode = Remote). /// Supply the broker URL through deployment configuration when remote analysis is enabled. diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj index f647dc2..a6de5c9 100644 --- a/src/Heimdall.Agent/Heimdall.Agent.csproj +++ b/src/Heimdall.Agent/Heimdall.Agent.csproj @@ -9,6 +9,14 @@ $(NoWarn);NU1902 + + + packages.gpu.lock.json + + + packages.lock.json + + @@ -25,7 +33,8 @@ - + + diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index e1ef9a0..61c6d94 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -149,7 +149,9 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => new FrameAnalyzerService( sp.GetRequiredService>(), sp.GetRequiredService(), - sp.GetRequiredService())); + sp.GetRequiredService(), + inference: null, + inferenceExecutionProvider: sp.GetRequiredService>().Value.InferenceExecutionProvider)); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index 5518340..f512b32 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging; using Microsoft.ML.OnnxRuntime; using Microsoft.ML.OnnxRuntime.Tensors; using ImageMagick; +using OnnxSessionOptions = Microsoft.ML.OnnxRuntime.SessionOptions; namespace Heimdall.Agent.Services; @@ -50,7 +51,8 @@ public sealed class FrameAnalyzerService : IDisposable private long _rejectedFrames; public long RejectedFrames => Interlocked.Read(ref _rejectedFrames); public bool ModelAvailable => _modelLoaded; - public string ExecutionProvider => "CPUExecutionProvider"; + private string _executionProvider = OnnxExecutionProviderSelection.CpuProviderName; + public string ExecutionProvider => _executionProvider; private readonly CircuitBreaker? _circuitBreaker; private readonly PipelineDegradationManager? _degradationManager; @@ -109,7 +111,8 @@ public sealed class FrameAnalyzerService : IDisposable PipelineDegradationManager? degradationManager) : this(logger, circuitBreaker, degradationManager, null) { } internal FrameAnalyzerService(ILogger logger, CircuitBreaker? circuitBreaker, - PipelineDegradationManager? degradationManager, Func? inference, string? modelPath = null) + PipelineDegradationManager? degradationManager, Func? inference, + string? modelPath = null, string inferenceExecutionProvider = "CPU") { _testInference = inference; _logger = logger; @@ -122,13 +125,7 @@ public sealed class FrameAnalyzerService : IDisposable { try { - using var sessionOptions = new Microsoft.ML.OnnxRuntime.SessionOptions - { - InterOpNumThreads = 1, - IntraOpNumThreads = 2, // spec §16: limit CPU threads for agent - GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, - }; - _session = new InferenceSession(_modelPath, sessionOptions); + _session = CreateSession(_modelPath, inferenceExecutionProvider, out _executionProvider); _inputName = _session.InputMetadata.Keys.Single(); var input = _session.InputMetadata[_inputName]; var output = _session.OutputMetadata.Values.Single(); @@ -169,6 +166,37 @@ public sealed class FrameAnalyzerService : IDisposable _processingLoop = Task.Run(() => ProcessingLoopAsync(_cts.Token)); } + private InferenceSession CreateSession(string modelPath, string requestedProvider, out string actualProvider) + { + var availableProviders = OrtEnv.Instance().GetAvailableProviders(); + return OnnxExecutionProviderSelection.CreateSession( + requestedProvider, + availableProviders, + () => + { + using var options = OnnxSessionOptions.MakeSessionOptionWithCudaProvider(0); + ConfigureSessionOptions(options); + return new InferenceSession(modelPath, options); + }, + () => + { + using var options = new OnnxSessionOptions(); + ConfigureSessionOptions(options); + return new InferenceSession(modelPath, options); + }, + reason => _logger.LogWarning( + "CUDA ONNX execution provider could not be used ({Reason}); falling back to CPU", + reason), + out actualProvider); + } + + private static void ConfigureSessionOptions(OnnxSessionOptions options) + { + options.InterOpNumThreads = 1; + options.IntraOpNumThreads = 2; // Limit CPU threads for Agent even when CUDA is preferred. + options.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL; + } + /// /// Submit a JPEG frame for analysis. Returns a task that completes when /// analysis is done. If the queue is full, explicitly rejects the new frame. diff --git a/src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs b/src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs new file mode 100644 index 0000000..672ad3d --- /dev/null +++ b/src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs @@ -0,0 +1,51 @@ +namespace Heimdall.Agent.Services; + +/// Builds an ONNX session using the requested provider when the runtime can attach it, otherwise using CPU. +internal static class OnnxExecutionProviderSelection +{ + public const string CpuProviderName = "CPUExecutionProvider"; + public const string CudaProviderName = "CUDAExecutionProvider"; + + public static TSession CreateSession( + string requestedProvider, + IReadOnlyCollection availableProviders, + Func createCudaSession, + Func createCpuSession, + Action reportFallback, + out string actualProvider) + where TSession : class + { + ArgumentNullException.ThrowIfNull(availableProviders); + ArgumentNullException.ThrowIfNull(createCudaSession); + ArgumentNullException.ThrowIfNull(createCpuSession); + ArgumentNullException.ThrowIfNull(reportFallback); + + if (string.Equals(requestedProvider, "CUDA", StringComparison.OrdinalIgnoreCase)) + { + if (availableProviders.Contains(CudaProviderName, StringComparer.Ordinal)) + { + try + { + var cudaSession = createCudaSession(); + if (cudaSession is not null) + { + actualProvider = CudaProviderName; + return cudaSession; + } + reportFallback("CUDA session creation returned no session"); + } + catch (Exception ex) when (ex is not OutOfMemoryException and not StackOverflowException) + { + reportFallback(ex.GetType().Name); + } + } + else + { + reportFallback("CUDAExecutionProvider is not registered in this ONNX Runtime build"); + } + } + + actualProvider = CpuProviderName; + return createCpuSession(); + } +} diff --git a/src/Heimdall.Agent/appsettings.json b/src/Heimdall.Agent/appsettings.json index bc4f385..e5aab72 100644 --- a/src/Heimdall.Agent/appsettings.json +++ b/src/Heimdall.Agent/appsettings.json @@ -11,7 +11,8 @@ "SiteToken": "", "AgentName": "", "HeartbeatIntervalSeconds": 30, - "RegistrationMaxRetries": 5 + "RegistrationMaxRetries": 5, + "InferenceExecutionProvider": "CPU" }, // Sentry/GlitchTip — DSN is read from Sentry:Dsn (or env Sentry__Dsn / legacy SENTRY_DSN) // When null/empty, Sentry SDK is not initialized (graceful no-op). diff --git a/src/Heimdall.Agent/packages.gpu.lock.json b/src/Heimdall.Agent/packages.gpu.lock.json new file mode 100644 index 0000000..1b7924e --- /dev/null +++ b/src/Heimdall.Agent/packages.gpu.lock.json @@ -0,0 +1,357 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Magick.NET-Q16-AnyCPU": { + "type": "Direct", + "requested": "[14.16.0, )", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Microsoft.AspNetCore.SignalR.Client": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "17fMUI5gkRwR9qXXTELd5OChcFn3lkgWpiblaaELQ45zOL7VuU7HJYAYnMk+Irjf2jpRxHT7b0imy+NVIFyoYQ==", + "dependencies": { + "Microsoft.AspNetCore.Http.Connections.Client": "10.0.13", + "Microsoft.AspNetCore.SignalR.Client.Core": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.Extensions.Hosting.WindowsServices": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "sk3VNcYEmgwYGPF4ze/112jpaeDKSsKGhmEZ8IlhOR8F6JT+1DYaZUb14jobVXiKhuXWIKcYXV7mkSPeA4dc3g==", + "dependencies": { + "System.ServiceProcess.ServiceController": "10.0.13" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu": { + "type": "Direct", + "requested": "[1.22.0, )", + "resolved": "1.22.0", + "contentHash": "3Fg/O8sSwty6fCVg7pl2Xk1ROXiJOCOKr+8dQWNh8v1Be16RyF/PHugNSncasCb1yts5zB1jk4Ci+Q66I+ge4w==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Gpu.Linux": "1.22.0", + "Microsoft.ML.OnnxRuntime.Gpu.Windows": "1.22.0", + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "OpenTelemetry": { + "type": "Direct", + "requested": "[1.17.0, )", + "resolved": "1.17.0", + "contentHash": "rMLOTftlMlTm7+MSrvXDHnJRjVkROFNKXHZrYjOsX+LankaFG7QSflx7qRRGjoqZoirohnxmJQ7GEb9occO4Gg==", + "dependencies": { + "OpenTelemetry.Api.ProviderBuilderExtensions": "1.17.0" + } + }, + "OpenTelemetry.Exporter.Prometheus.AspNetCore": { + "type": "Direct", + "requested": "[1.17.0-beta.1, )", + "resolved": "1.17.0-beta.1", + "contentHash": "eecXu43HkY7LFJDutrQ6kpwvUOMDeqLMtU+UeN225ckXw33qN/StTcdW6mTHH1jDSYdFM29vvDXB3jnFwPHkXg==", + "dependencies": { + "OpenTelemetry": "[1.17.0, 2.0.0)" + } + }, + "OpenTelemetry.Extensions.Hosting": { + "type": "Direct", + "requested": "[1.17.0, )", + "resolved": "1.17.0", + "contentHash": "t1OwL/4qgboGMobYVT+UV5zgWnFqCp4Pw8lcsmzh8m2K8PQsTKkyxrC32tqYTMYny3GOW4q5cltE3dTVzLmRew==", + "dependencies": { + "OpenTelemetry": "1.17.0" + } + }, + "Sentry.AspNetCore": { + "type": "Direct", + "requested": "[6.8.0, )", + "resolved": "6.8.0", + "contentHash": "yo9TeFZPgmhyu0Vj+Zq3VxRR8kDbhlNbRAQDANN+gTwETe5uDa/H1I91PntBD7jwhWa7P218bYU+LGYOipylYA==", + "dependencies": { + "Sentry.Extensions.Logging": "6.8.0" + } + }, + "AutoMapper": { + "type": "Transitive", + "resolved": "16.1.1", + "contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.14.0" + } + }, + "FluentValidation": { + "type": "Transitive", + "resolved": "11.11.0", + "contentHash": "cyIVdQBwSipxWG8MA3Rqox7iNbUNUTK5bfJi9tIdm4CAfH71Oo5ABLP4/QyrUwuakqpUEPGtE43BDddvEehuYw==" + }, + "FluentValidation.DependencyInjectionExtensions": { + "type": "Transitive", + "resolved": "11.11.0", + "contentHash": "viTKWaMbL3yJYgGI0DiCeavNbE9UPMWFVK2XS9nYXGbm3NDMd0/L5ER4wBzmTtW3BYh3SrlSXm9RACiKZ6stlA==", + "dependencies": { + "FluentValidation": "11.11.0" + } + }, + "Magick.NET.Core": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ==" + }, + "MediatR": { + "type": "Transitive", + "resolved": "12.5.0", + "contentHash": "vqm2H8/nqL5NAJHPhsG1JOPwfkmbVrPyh4svdoRzu+uZh6Ex7PRoHBGsLYC0/RWCEJFqD1ohHNpteQvql9OktA==", + "dependencies": { + "MediatR.Contracts": "[2.0.1, 3.0.0)" + } + }, + "MediatR.Contracts": { + "type": "Transitive", + "resolved": "2.0.1", + "contentHash": "FYv95bNT4UwcNA+G/J1oX5OpRiSUxteXaUt2BJbRSdRNiIUNbggJF69wy6mnk2wYToaanpdXZdCwVylt96MpwQ==" + }, + "Microsoft.AspNetCore.Http.Connections.Client": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "r9hlU+te+QWFJlUCt2C22TDKY3oMER8ayC7Qzeq6yJ5toHBKcSqshhyyaLKK1jgBuyNi4ejly0wE8ANV8TyfWQ==" + }, + "Microsoft.AspNetCore.SignalR.Client.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zfCQ0/J/rATKKcpwcpQYFz8sxhvrzgGyblsATcfxqSCibRkPFmDZcFmfD0UfLi38q+VDMpwEVuzOCO3TpRy99Q==" + }, + "Microsoft.Data.Sqlite": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "w37nz3WFmDtRfXxWEwIXX2OgqDRiwhD1JGbFwfpFCF8GkCrV/yO6Y2JF5058J2RGoI2sCcdn02wrk0yEcekWcw==", + "dependencies": { + "Microsoft.Data.Sqlite.Core": "10.0.13", + "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.Data.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "Gge8XsSCOwcbkbdmt2UDAe6kIv9Q0vA6yb3wsTStjjexaMFLTWfc/1gH4kbhJ+zWiXRTRA4lG2sOQNVfir204w==", + "dependencies": { + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.EntityFrameworkCore": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Abstractions": "10.0.13", + "Microsoft.EntityFrameworkCore.Analyzers": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A==" + }, + "Microsoft.EntityFrameworkCore.Analyzers": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA==" + }, + "Microsoft.EntityFrameworkCore.Relational": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==", + "dependencies": { + "Microsoft.EntityFrameworkCore": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==", + "dependencies": { + "Microsoft.Data.Sqlite.Core": "10.0.13", + "Microsoft.EntityFrameworkCore.Relational": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ==" + }, + "Microsoft.IdentityModel.Abstractions": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "iwbCpSjD3ehfTwBhtSNEtKPK0ICun6ov7Ibx6ISNA9bfwIyzI2Siwyi9eJFCJBwxowK9xcA1mj+jBWiigeqgcQ==" + }, + "Microsoft.IdentityModel.JsonWebTokens": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "4jOpiA4THdtpLyMdAb24dtj7+6GmvhOhxf5XHLYWmPKF8ApEnApal1UnJsKO4HxUWRXDA6C4WQVfYyqsRhpNpQ==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.14.0" + } + }, + "Microsoft.IdentityModel.Logging": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "eqqnemdW38CKZEHS6diA50BV94QICozDZEvSrsvN3SJXUFwVB9gy+/oz76gldP7nZliA16IglXjXTCTdmU/Ejg==", + "dependencies": { + "Microsoft.IdentityModel.Abstractions": "8.14.0" + } + }, + "Microsoft.IdentityModel.Tokens": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "lKIZiBiGd36k02TCdMHp1KlNWisyIvQxcYJvIkz7P4gSQ9zi8dgh6S5Grj8NNG7HWYIPfQymGyoZ6JB5d1Lo1g==", + "dependencies": { + "Microsoft.IdentityModel.Logging": "8.14.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Linux": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "1llC85TrCC69e18WSBF5rAHnbvwLY9wI+wX8PUpMfQhtSehZlJImMfXoCEdPYTtvLR/5ad/wHG43LwRLSxqp+g==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Windows": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "vscA3rOmdgyOXeXWMheBC4okYGvoHEK3bOC/RudikJyR3wY4mbiukfUqa94etShJ+YQYA9q35DOz0bxrAOUOKw==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "Microsoft.ML.OnnxRuntime.Managed": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "zlG3eY5mJnx1BhYAxRwpuHCGHzl3B+cY5/se0RmlVBw6Yh6QTGjPAXdjhlBIcw6BPFhgMn9lxWPE/U3Fvis+BQ==", + "dependencies": { + "System.Numerics.Tensors": "9.0.0" + } + }, + "OpenTelemetry.Api": { + "type": "Transitive", + "resolved": "1.17.0", + "contentHash": "mSBxzomZgHIJu9CyVNqyDu/n2JHEtqVgfcCD1Br0cV5iLYogjZOMqhlVLt99PEp+0KGBNUR3GXgeOdN2GR3F9g==" + }, + "OpenTelemetry.Api.ProviderBuilderExtensions": { + "type": "Transitive", + "resolved": "1.17.0", + "contentHash": "Xgc3Qf9B9TFMFpx6exTdGqMWuYIT2miNzkdMPutVvT9YuMFaEovXWke1Gb6z8NxYaQbbGF38vYLuSg1JCeui5Q==", + "dependencies": { + "OpenTelemetry.Api": "1.17.0" + } + }, + "Sentry": { + "type": "Transitive", + "resolved": "6.8.0", + "contentHash": "amUjwslDtdx1p8r6z4APCxM8vHCKG4CBamPpSTwxmTMoBQ2CLwx2m3CaIttJXRT/hw9S5rNfXgjol2OqADytLQ==" + }, + "Sentry.Extensions.Logging": { + "type": "Transitive", + "resolved": "6.8.0", + "contentHash": "K7/Z7B8ec5c61ByzZOgxHxhcT+5yo7X6n7GchcaFI/X44Zn/ZsGqUFMqvypaILnc4JISAeppDTSiWdgWmflzbg==", + "dependencies": { + "Sentry": "6.8.0" + } + }, + "SQLite": { + "type": "Transitive", + "resolved": "3.53.4", + "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" + }, + "SQLitePCLRaw.bundle_e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "SW8iASIyWMrLzqabUHYQRvALhvD4ylSBsj4PgEVGwc36kQjc9xT5kSV/XQ9rU7nIpBWD+LPyX3Hlw5FzyUzGeQ==", + "dependencies": { + "SQLite": "3.53.4", + "SQLitePCLRaw.config.e_sqlite3": "3.0.5" + } + }, + "SQLitePCLRaw.config.e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "aSk8WE5tF2MybESMgtZAEyMVCAWA0nBqOMc48HFoa9UoSdtm3goDXVzNRnefeKIwE6bV9NaNXptn1F9ReMQI0Q==", + "dependencies": { + "SQLitePCLRaw.provider.e_sqlite3": "3.0.5" + } + }, + "SQLitePCLRaw.core": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "k81AYXXRCw3Zj8rOhyBoCsx/U97KYDFI2CSKr/ijl5BwpsW/hX/4kBiDmerFaoust8nxBwa0IHQFw8MmSHRtnQ==" + }, + "SQLitePCLRaw.provider.e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "um8YSWduhhuskTG2bHfZrBqMNQOydfU8pcseT+cu5RivOGyoUbCrGXxgoRNTmRYw2VbMWnEZVVFcneZT/5dsBg==", + "dependencies": { + "SQLitePCLRaw.core": "3.0.5" + } + }, + "System.Numerics.Tensors": { + "type": "Transitive", + "resolved": "9.0.0", + "contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A==" + }, + "System.ServiceProcess.ServiceController": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ==" + }, + "heimdall.application": { + "type": "Project", + "dependencies": { + "AutoMapper": "[16.1.1, )", + "FluentValidation": "[11.11.0, )", + "FluentValidation.DependencyInjectionExtensions": "[11.11.0, )", + "Heimdall.Domain": "[1.0.0, )", + "MediatR": "[12.5.0, )", + "Microsoft.Data.Sqlite": "[10.0.13, )", + "Microsoft.EntityFrameworkCore": "[10.0.13, )", + "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )", + "SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )" + } + }, + "heimdall.contracts": { + "type": "Project" + }, + "heimdall.domain": { + "type": "Project", + "dependencies": { + "Heimdall.Domain.Primitives": "[1.0.0, )" + } + }, + "heimdall.domain.primitives": { + "type": "Project" + }, + "heimdall.mdns": { + "type": "Project" + } + } + } +} \ No newline at end of file diff --git a/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj b/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj index ae84830..3f4c743 100644 --- a/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj +++ b/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj @@ -7,6 +7,13 @@ false + + packages.gpu.lock.json + + + packages.lock.json + + diff --git a/tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs b/tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs new file mode 100644 index 0000000..8c0da79 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs @@ -0,0 +1,77 @@ +using Heimdall.Agent.Services; + +namespace Heimdall.Agent.Tests; + +public sealed class OnnxExecutionProviderSelectionTests +{ + [Fact] + public void CreateSession_CpuRequest_UsesOnlyCpu() + { + var cudaCalls = 0; + var fallbacks = new List(); + + var session = OnnxExecutionProviderSelection.CreateSession( + "CPU", + [OnnxExecutionProviderSelection.CudaProviderName, OnnxExecutionProviderSelection.CpuProviderName], + () => { cudaCalls++; return "cuda"; }, + () => "cpu", + fallbacks.Add, + out var actualProvider); + + session.ShouldBe("cpu"); + cudaCalls.ShouldBe(0); + fallbacks.ShouldBeEmpty(); + actualProvider.ShouldBe(OnnxExecutionProviderSelection.CpuProviderName); + } + + [Fact] + public void CreateSession_CudaRegisteredAndCreated_ReportsCuda() + { + var session = OnnxExecutionProviderSelection.CreateSession( + "CUDA", + [OnnxExecutionProviderSelection.CudaProviderName], + () => "cuda", + () => "cpu", + _ => throw new InvalidOperationException("Unexpected fallback"), + out var actualProvider); + + session.ShouldBe("cuda"); + actualProvider.ShouldBe(OnnxExecutionProviderSelection.CudaProviderName); + } + + [Fact] + public void CreateSession_CudaNotRegistered_FallsBackToCpu() + { + var fallbacks = new List(); + + var session = OnnxExecutionProviderSelection.CreateSession( + "CUDA", + [OnnxExecutionProviderSelection.CpuProviderName], + () => "cuda", + () => "cpu", + fallbacks.Add, + out var actualProvider); + + session.ShouldBe("cpu"); + fallbacks.ShouldContain("CUDAExecutionProvider is not registered in this ONNX Runtime build"); + actualProvider.ShouldBe(OnnxExecutionProviderSelection.CpuProviderName); + } + + [Fact] + public void CreateSession_CudaInitializationFails_FallsBackToCpu() + { + var fallbacks = new List(); + + var session = OnnxExecutionProviderSelection.CreateSession( + "CUDA", + [OnnxExecutionProviderSelection.CudaProviderName], + () => throw new DllNotFoundException("synthetic missing CUDA runtime"), + () => "cpu", + fallbacks.Add, + out var actualProvider); + + session.ShouldBe("cpu"); + fallbacks.ShouldContain(nameof(DllNotFoundException)); + actualProvider.ShouldBe(OnnxExecutionProviderSelection.CpuProviderName); + } +} diff --git a/tests/Heimdall.Agent.Tests/packages.gpu.lock.json b/tests/Heimdall.Agent.Tests/packages.gpu.lock.json new file mode 100644 index 0000000..d8db8a4 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/packages.gpu.lock.json @@ -0,0 +1,953 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "coverlet.collector": { + "type": "Direct", + "requested": "[6.0.4, )", + "resolved": "6.0.4", + "contentHash": "lkhqpF8Pu2Y7IiN7OntbsTtdbpR1syMsm2F3IgX6ootA4ffRqWL5jF7XipHuZQTdVuWG/gVAAcf8mjk8Tz0xPg==" + }, + "Microsoft.AspNetCore.DataProtection": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "d8y1BVJdef2IPunLS6nPAHwmH162gQ7wGrv17jXcPPdFSjD4GgTUE7OHM0s57Z80tNFb/iRxQUBsNNXzYs/C/w==", + "dependencies": { + "Microsoft.AspNetCore.Cryptography.Internal": "10.0.13", + "Microsoft.AspNetCore.DataProtection.Abstractions": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "System.Security.Cryptography.Xml": "10.0.13" + } + }, + "Microsoft.Data.Sqlite": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "w37nz3WFmDtRfXxWEwIXX2OgqDRiwhD1JGbFwfpFCF8GkCrV/yO6Y2JF5058J2RGoI2sCcdn02wrk0yEcekWcw==", + "dependencies": { + "Microsoft.Data.Sqlite.Core": "10.0.13", + "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[17.14.1, )", + "resolved": "17.14.1", + "contentHash": "HJKqKOE+vshXra2aEHpi2TlxYX7Z9VFYkr+E5rwEvHC8eIXiyO+K9kNm8vmNom3e2rA56WqxU+/N9NJlLGXsJQ==", + "dependencies": { + "Microsoft.CodeCoverage": "17.14.1", + "Microsoft.TestPlatform.TestHost": "17.14.1" + } + }, + "NSubstitute": { + "type": "Direct", + "requested": "[6.0.0, )", + "resolved": "6.0.0", + "contentHash": "0gvKMbiJ+/WrfbcfBfqRZZrvfLJcd3rqkqVMjjlY5dtmLRVzMY+o/K/rJUStofQ2haSr9Vd04YDfvZtVVGS3/A==", + "dependencies": { + "Castle.Core": "5.1.1" + } + }, + "Shouldly": { + "type": "Direct", + "requested": "[4.3.0, )", + "resolved": "4.3.0", + "contentHash": "sDetrWXrl6YXZ4HeLsdBoNk3uIa7K+V4uvIJ+cqdRa5DrFxeTED7VkjoxCuU1kJWpUuBDZz2QXFzSxBtVXLwRQ==", + "dependencies": { + "DiffEngine": "11.3.0", + "EmptyFiles": "4.4.0" + } + }, + "xunit": { + "type": "Direct", + "requested": "[2.9.3, )", + "resolved": "2.9.3", + "contentHash": "TlXQBinK35LpOPKHAqbLY4xlEen9TBafjs0V5KnA4wZsoQLQJiirCR4CbIXvOH8NzkW4YeJKP5P/Bnrodm0h9Q==", + "dependencies": { + "xunit.analyzers": "1.18.0", + "xunit.assert": "2.9.3", + "xunit.core": "[2.9.3]" + } + }, + "xunit.runner.visualstudio": { + "type": "Direct", + "requested": "[3.1.4, )", + "resolved": "3.1.4", + "contentHash": "5mj99LvCqrq3CNi06xYdyIAXOEh+5b33F2nErCzI5zWiDdLHXiPXEWFSUAF8zlIv0ZWqjZNCwHTQeAPYbF3pCg==" + }, + "AutoMapper": { + "type": "Transitive", + "resolved": "16.1.1", + "contentHash": "VNEky8JA15ci+oIDRGHITOGOpV4dILsf8pnn24QhDl2urtqgJ2IXiS/V2EtGU17P/+f6OeFQPJETaZXV9QOIZg==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "10.0.0", + "Microsoft.Extensions.Options": "10.0.0", + "Microsoft.IdentityModel.JsonWebTokens": "8.14.0" + } + }, + "Castle.Core": { + "type": "Transitive", + "resolved": "5.1.1", + "contentHash": "rpYtIczkzGpf+EkZgDr9CClTdemhsrwA/W5hMoPjLkRFnXzH44zDLoovXeKtmxb1ykXK9aJVODSpiJml8CTw2g==", + "dependencies": { + "System.Diagnostics.EventLog": "6.0.0" + } + }, + "DiffEngine": { + "type": "Transitive", + "resolved": "11.3.0", + "contentHash": "k0ZgZqd09jLZQjR8FyQbSQE86Q7QZnjEzq1LPHtj1R2AoWO8sjV5x+jlSisL7NZAbUOI4y+7Bog8gkr9WIRBGw==", + "dependencies": { + "EmptyFiles": "4.4.0", + "System.Management": "6.0.1" + } + }, + "EmptyFiles": { + "type": "Transitive", + "resolved": "4.4.0", + "contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw==" + }, + "FluentValidation": { + "type": "Transitive", + "resolved": "11.11.0", + "contentHash": "cyIVdQBwSipxWG8MA3Rqox7iNbUNUTK5bfJi9tIdm4CAfH71Oo5ABLP4/QyrUwuakqpUEPGtE43BDddvEehuYw==" + }, + "FluentValidation.DependencyInjectionExtensions": { + "type": "Transitive", + "resolved": "11.11.0", + "contentHash": "viTKWaMbL3yJYgGI0DiCeavNbE9UPMWFVK2XS9nYXGbm3NDMd0/L5ER4wBzmTtW3BYh3SrlSXm9RACiKZ6stlA==", + "dependencies": { + "FluentValidation": "11.11.0", + "Microsoft.Extensions.Dependencyinjection.Abstractions": "2.1.0" + } + }, + "Magick.NET-Q16-AnyCPU": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Magick.NET.Core": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ==" + }, + "MediatR": { + "type": "Transitive", + "resolved": "12.5.0", + "contentHash": "vqm2H8/nqL5NAJHPhsG1JOPwfkmbVrPyh4svdoRzu+uZh6Ex7PRoHBGsLYC0/RWCEJFqD1ohHNpteQvql9OktA==", + "dependencies": { + "MediatR.Contracts": "[2.0.1, 3.0.0)", + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0" + } + }, + "MediatR.Contracts": { + "type": "Transitive", + "resolved": "2.0.1", + "contentHash": "FYv95bNT4UwcNA+G/J1oX5OpRiSUxteXaUt2BJbRSdRNiIUNbggJF69wy6mnk2wYToaanpdXZdCwVylt96MpwQ==" + }, + "Microsoft.AspNetCore.Connections.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "l/1VmXALhXxdTWG+41N25xigbAXZx/43c6cVw+mXxLH6KCKO25P3c53MLK5w5ua0GCr2RdZhN/xsUwCG7v9N1w==", + "dependencies": { + "Microsoft.Extensions.Features": "10.0.13" + } + }, + "Microsoft.AspNetCore.Cryptography.Internal": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA==" + }, + "Microsoft.AspNetCore.DataProtection.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "ZeGcJpE6GpYVL2/4Lk0zkkTxf8a5hvTT91ApVf4BZA21GFQ4HY6gOpgPD1+4ED/43errbY8RwKyQynlT1kI33Q==" + }, + "Microsoft.AspNetCore.Http.Connections.Client": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "r9hlU+te+QWFJlUCt2C22TDKY3oMER8ayC7Qzeq6yJ5toHBKcSqshhyyaLKK1jgBuyNi4ejly0wE8ANV8TyfWQ==", + "dependencies": { + "Microsoft.AspNetCore.Http.Connections.Common": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.AspNetCore.Http.Connections.Common": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "L3NCYBsvQIcSS+qu6TemunsNGEDk29hLchifeBcg7kcriAwfKJSUPyF34zVzFTfsgnza531SMynbNr7g1tcq0Q==", + "dependencies": { + "Microsoft.AspNetCore.Connections.Abstractions": "10.0.13" + } + }, + "Microsoft.AspNetCore.SignalR.Client": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "17fMUI5gkRwR9qXXTELd5OChcFn3lkgWpiblaaELQ45zOL7VuU7HJYAYnMk+Irjf2jpRxHT7b0imy+NVIFyoYQ==", + "dependencies": { + "Microsoft.AspNetCore.Http.Connections.Client": "10.0.13", + "Microsoft.AspNetCore.SignalR.Client.Core": "10.0.13" + } + }, + "Microsoft.AspNetCore.SignalR.Client.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zfCQ0/J/rATKKcpwcpQYFz8sxhvrzgGyblsATcfxqSCibRkPFmDZcFmfD0UfLi38q+VDMpwEVuzOCO3TpRy99Q==", + "dependencies": { + "Microsoft.AspNetCore.SignalR.Common": "10.0.13", + "Microsoft.AspNetCore.SignalR.Protocols.Json": "10.0.13", + "Microsoft.Extensions.DependencyInjection": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13" + } + }, + "Microsoft.AspNetCore.SignalR.Common": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "Rd6v57QqwW7Uayx0//qsf6J8MGcdw4Lw3Bq3dfT33KWnydaf0HsXoBxHQze/EowSsYQUx2yi9+PWCob9A9GuFw==", + "dependencies": { + "Microsoft.AspNetCore.Connections.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.AspNetCore.SignalR.Protocols.Json": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "8TvhozBxdbcmS+4S4mb2FN2ls5NU99zwapQAUIse8oWV7CwvUTq0bBJ5/0+0B0JW9wnrxBpMrJ6jkivnG+f7fg==", + "dependencies": { + "Microsoft.AspNetCore.SignalR.Common": "10.0.13" + } + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "pmTrhfFIoplzFVbhVwUquT+77CbGH+h4/3mBpdmIlYtBi9nAB+kKI6dN3A/nV4DFi3wLLx/BlHIPK+MkbQ6Tpg==" + }, + "Microsoft.Data.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "Gge8XsSCOwcbkbdmt2UDAe6kIv9Q0vA6yb3wsTStjjexaMFLTWfc/1gH4kbhJ+zWiXRTRA4lG2sOQNVfir204w==", + "dependencies": { + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.EntityFrameworkCore": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Abstractions": "10.0.13", + "Microsoft.EntityFrameworkCore.Analyzers": "10.0.13", + "Microsoft.Extensions.Caching.Memory": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A==" + }, + "Microsoft.EntityFrameworkCore.Analyzers": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA==" + }, + "Microsoft.EntityFrameworkCore.Relational": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==", + "dependencies": { + "Microsoft.EntityFrameworkCore": "10.0.13", + "Microsoft.Extensions.Caching.Memory": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "CqPgFVpKjdNjPHO1fqK5Uw/h7RfY6LyjPko9cLiXTBkxUhjO0Bt48tnF/ddw5PL2k5JaR8myDcyogcONY7juLg==", + "dependencies": { + "Microsoft.EntityFrameworkCore.Sqlite.Core": "10.0.13", + "Microsoft.Extensions.Caching.Memory": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "SQLitePCLRaw.bundle_e_sqlite3": "2.1.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.EntityFrameworkCore.Sqlite.Core": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zXJAJOS34unH9sWP6ywyUmaZ/yeHy0/CljvdsHvzhN/rXHRBXsPRYymTU65my0rGoa60mh7HUXVPEGOxfsiWSg==", + "dependencies": { + "Microsoft.Data.Sqlite.Core": "10.0.13", + "Microsoft.EntityFrameworkCore.Relational": "10.0.13", + "Microsoft.Extensions.Caching.Memory": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.DependencyModel": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "SQLitePCLRaw.core": "2.1.13" + } + }, + "Microsoft.Extensions.Caching.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "UOJqcdNMoFcV/5RUcOlVKq9pPmbrcmbpLx5iYz9QtrmMcWRQzlL5Q/NZRfbPPLNyIEc1HWjjs5Z7nIwqewU1sg==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Caching.Memory": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "q+At65RACuCtGwUDVI08TmmrC73YFouimMkJAtlhsGhFcU/dVpqYEKpNBOF9TUxkJ6aefEOShqe7StLK7q3NqA==", + "dependencies": { + "Microsoft.Extensions.Caching.Abstractions": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "DY4C2qzTt2lOIY3VoscBH/TCwTolI5DKOfgJLuI+k1QUvRNT5vTMS58AOerNiihdVRStO0wEpLeRWA8jytzHBQ==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.CommandLine": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "RwdNZ9JdGs8eZmeL5qRe7ugp0Irk3KVkWpC/w1c8kjJwu1R4HvCXYz9kwHZxn45WiaRBG5lphQKtqnBaJOQC+Q==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.EnvironmentVariables": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "qJK2dm9/AxyPVfqqBaZtjkUFl2hnBR/CQnMJtSO5LdEoyATMqvZjeQVY+8l0oa6PM6qlVe28iMEyXIRQ0wyZjA==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.FileExtensions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "kwC1DY55CsqPmDtJAz+7alD3G+gJcM+XwHSZrcRO8mJGYB9hRq1qC6ZH8DL0SPW9WtJ/Bae5ikzPic8SxSv6Vw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Physical": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.Json": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "acCWM2+WR67kBAz6gAhD2zG+IZH9Q2VpKv5le7Msiu0vAMsnnLXpnV3BAzxd8/i+uOEo/dfb2XRYTynRVTDvEg==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.FileExtensions": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Configuration.UserSecrets": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "kQ/Tx972unP+ueQL8SSninthIj6w6XP2o0VnJPFC5HQIimPMwEN704MOspEgDkmm4FUL5SuxLEU0bNiW4HEZFA==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Json": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Physical": "10.0.13" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "4tnWU9vrU/A8NwYe9Z6wvieZ0EBb/uM82LAT+edNhdepOBWREZ7M7mzb941EIDPJaeOFdbVrDd5+7s9e89U6bQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ==" + }, + "Microsoft.Extensions.DependencyModel": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ==" + }, + "Microsoft.Extensions.Diagnostics": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.Features": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "7xLogOKNBYYWbUUEMOPfuirfcYG8iBNQ4TOc3aUzJpiRD7tyQqzYWhDPXAk2kOuJTd7ImcGtdT1HEQTC9VljuQ==" + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "BZDwtN3uoWRghDi5lRRZPDjMMCg2Ds7J6YEYjqka/TLjqnzquEpXyvchrIMeoubwT1ns23ow6PPeAoBHJO81Rw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.FileProviders.Physical": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "U7HkgGCNPICN5k7NVK6dmLsSPSPeO/EbNcuxOl/5qdC9Ahjp9UZWKOvlnUC+rYurmoxIlwyv9e5j0BaQlTOELA==", + "dependencies": { + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileSystemGlobbing": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.FileSystemGlobbing": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "vQVzmAbnzlhXSXA2caYnlxtG9GXxEwtj5bODiWLu06A6iqeJmfBtlfKjuOSJGRy0/CFaNUrm7u9nxEUlljc2Rg==" + }, + "Microsoft.Extensions.Hosting": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "Q+hmPoDqeHipHyJcY7mDCQiLDUcn9jIgjoCThcgaOgjLTTT3ApTe8p6M2+twsDyfKuuCsKhSNlnNjaaggtXxRA==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Binder": "10.0.13", + "Microsoft.Extensions.Configuration.CommandLine": "10.0.13", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.13", + "Microsoft.Extensions.Configuration.FileExtensions": "10.0.13", + "Microsoft.Extensions.Configuration.Json": "10.0.13", + "Microsoft.Extensions.Configuration.UserSecrets": "10.0.13", + "Microsoft.Extensions.DependencyInjection": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Diagnostics": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Physical": "10.0.13", + "Microsoft.Extensions.Hosting.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Configuration": "10.0.13", + "Microsoft.Extensions.Logging.Console": "10.0.13", + "Microsoft.Extensions.Logging.Debug": "10.0.13", + "Microsoft.Extensions.Logging.EventLog": "10.0.13", + "Microsoft.Extensions.Logging.EventSource": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "zIrbe9vkIFXxW3mOApIOWXw+xMwX7Cgsptr3ZSlglJt4hW2qp4fB/JU1NHgAevteBNH4PicvU9DsFPHxlnnloA==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13", + "Microsoft.Extensions.FileProviders.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Hosting.WindowsServices": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "sk3VNcYEmgwYGPF4ze/112jpaeDKSsKGhmEZ8IlhOR8F6JT+1DYaZUb14jobVXiKhuXWIKcYXV7mkSPeA4dc3g==", + "dependencies": { + "Microsoft.Extensions.Hosting": "10.0.13", + "Microsoft.Extensions.Logging.EventLog": "10.0.13", + "System.ServiceProcess.ServiceController": "10.0.13" + } + }, + "Microsoft.Extensions.Http": { + "type": "Transitive", + "resolved": "10.0.0", + "contentHash": "r+mSvm/Ryc/iYcc9zcUG5VP9EBB8PL1rgVU6macEaYk45vmGRk9PntM3aynFKN6s3Q4WW36kedTycIctctpTUQ==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", + "Microsoft.Extensions.Diagnostics": "10.0.0", + "Microsoft.Extensions.Logging": "10.0.0", + "Microsoft.Extensions.Logging.Abstractions": "10.0.0", + "Microsoft.Extensions.Options": "10.0.0" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "fqbiPy4nUp4H2XHKAVQXKN2y3T2h4cFIx1DAAgE6iY9OHkN/OA1cKFi+geJKRWGuX6pS5SFbsjIPWHJqrxE0eg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "aSZEhEig4fvNiw2zs8Z6NyDlniKtq6YjcF3DyHuqTEHcZ2VKA/6itMPZ+dW+yWABWExlDcQwwdbqX1Rcb7W8WQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Configuration": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "OyYJOaE9WbBx1Hp+Dd2zrqeFM0JwH5M/x0VL6tNUv3V18vIAVpix8UjhvY9eW/iXpguEHy68JO/Z9YkBOwftIw==", + "dependencies": { + "Microsoft.Extensions.Configuration": "10.0.13", + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Binder": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Console": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "i9rn0rHkiCxfNVbf4DRG7LOFcKPy/BioAxS07w6daWvIpLNRjskqDJcGGaYVFWndsq0iTRaS8Msry0t5fRYQug==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging.Configuration": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.Debug": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "yBig0DNMq+3UgliwxYlUC48dg0fPqvqI5B3ljzmLTrpR6maoKTOO5i9QnPgQUmQoaQWZMgu74fuF6oSDihb6pg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.EventLog": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "OAK40lXhgMuvyNwvzW3fxLvvucN8yr5XS7dQRcPmtnPf+Pt1lpbMgao5T4Wa6VdFagtIeDZNgPtV5Ig4xstziQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "System.Diagnostics.EventLog": "10.0.13" + } + }, + "Microsoft.Extensions.Logging.EventSource": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "SxJu3oczk+TJtHvpgAmCVzEkzx69/obA6GZCbGrbqYqc981YOAyfEprySBdFX7Yc5qatHJKHNTlpGeeBAQkZcA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Logging": "10.0.13", + "Microsoft.Extensions.Logging.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Options": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "tmMJgdrE4uhf1JcNs9CV9moAHW+hmDuvgMiPpnQxarKaUxqI2eN33sYK5S4l9Uw+rG9PJvlm4qPxMhvolTDTaQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "10.0.13", + "Microsoft.Extensions.Configuration.Binder": "10.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13", + "Microsoft.Extensions.Options": "10.0.13", + "Microsoft.Extensions.Primitives": "10.0.13" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "ZjTwxzhiw2TMEzIbUDkMF0dfDB2I4NQgIfKD0ELu9/5Mk+SRGdKZcD0/lvBrRCAPo6KN2r0BW86MRancoyJkoA==" + }, + "Microsoft.IdentityModel.Abstractions": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "iwbCpSjD3ehfTwBhtSNEtKPK0ICun6ov7Ibx6ISNA9bfwIyzI2Siwyi9eJFCJBwxowK9xcA1mj+jBWiigeqgcQ==" + }, + "Microsoft.IdentityModel.JsonWebTokens": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "4jOpiA4THdtpLyMdAb24dtj7+6GmvhOhxf5XHLYWmPKF8ApEnApal1UnJsKO4HxUWRXDA6C4WQVfYyqsRhpNpQ==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.14.0" + } + }, + "Microsoft.IdentityModel.Logging": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "eqqnemdW38CKZEHS6diA50BV94QICozDZEvSrsvN3SJXUFwVB9gy+/oz76gldP7nZliA16IglXjXTCTdmU/Ejg==", + "dependencies": { + "Microsoft.IdentityModel.Abstractions": "8.14.0" + } + }, + "Microsoft.IdentityModel.Tokens": { + "type": "Transitive", + "resolved": "8.14.0", + "contentHash": "lKIZiBiGd36k02TCdMHp1KlNWisyIvQxcYJvIkz7P4gSQ9zi8dgh6S5Grj8NNG7HWYIPfQymGyoZ6JB5d1Lo1g==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "8.0.0", + "Microsoft.IdentityModel.Logging": "8.14.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "3Fg/O8sSwty6fCVg7pl2Xk1ROXiJOCOKr+8dQWNh8v1Be16RyF/PHugNSncasCb1yts5zB1jk4Ci+Q66I+ge4w==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Gpu.Linux": "1.22.0", + "Microsoft.ML.OnnxRuntime.Gpu.Windows": "1.22.0", + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Linux": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "1llC85TrCC69e18WSBF5rAHnbvwLY9wI+wX8PUpMfQhtSehZlJImMfXoCEdPYTtvLR/5ad/wHG43LwRLSxqp+g==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Windows": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "vscA3rOmdgyOXeXWMheBC4okYGvoHEK3bOC/RudikJyR3wY4mbiukfUqa94etShJ+YQYA9q35DOz0bxrAOUOKw==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "Microsoft.ML.OnnxRuntime.Managed": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "zlG3eY5mJnx1BhYAxRwpuHCGHzl3B+cY5/se0RmlVBw6Yh6QTGjPAXdjhlBIcw6BPFhgMn9lxWPE/U3Fvis+BQ==", + "dependencies": { + "System.Numerics.Tensors": "9.0.0" + } + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "xTP1W6Mi6SWmuxd3a+jj9G9UoC850WGwZUps1Wah9r1ZxgXhdJfj1QqDLJkFjHDCvN42qDL2Ps5KjQYWUU0zcQ==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "d78LPzGKkJwsJXAQwsbJJ7LE7D1wB+rAyhHHAaODF+RDSQ0NgMjDFkSA1Djw18VrxO76GlKAjRUhl+H8NL8Z+Q==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "17.14.1", + "Newtonsoft.Json": "13.0.3" + } + }, + "Newtonsoft.Json": { + "type": "Transitive", + "resolved": "13.0.3", + "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" + }, + "OpenTelemetry": { + "type": "Transitive", + "resolved": "1.17.0", + "contentHash": "rMLOTftlMlTm7+MSrvXDHnJRjVkROFNKXHZrYjOsX+LankaFG7QSflx7qRRGjoqZoirohnxmJQ7GEb9occO4Gg==", + "dependencies": { + "Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.0", + "Microsoft.Extensions.Diagnostics.Abstractions": "10.0.0", + "Microsoft.Extensions.Logging.Configuration": "10.0.0", + "OpenTelemetry.Api.ProviderBuilderExtensions": "1.17.0" + } + }, + "OpenTelemetry.Api": { + "type": "Transitive", + "resolved": "1.17.0", + "contentHash": "mSBxzomZgHIJu9CyVNqyDu/n2JHEtqVgfcCD1Br0cV5iLYogjZOMqhlVLt99PEp+0KGBNUR3GXgeOdN2GR3F9g==" + }, + "OpenTelemetry.Api.ProviderBuilderExtensions": { + "type": "Transitive", + "resolved": "1.17.0", + "contentHash": "Xgc3Qf9B9TFMFpx6exTdGqMWuYIT2miNzkdMPutVvT9YuMFaEovXWke1Gb6z8NxYaQbbGF38vYLuSg1JCeui5Q==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0", + "OpenTelemetry.Api": "1.17.0" + } + }, + "OpenTelemetry.Exporter.Prometheus.AspNetCore": { + "type": "Transitive", + "resolved": "1.17.0-beta.1", + "contentHash": "eecXu43HkY7LFJDutrQ6kpwvUOMDeqLMtU+UeN225ckXw33qN/StTcdW6mTHH1jDSYdFM29vvDXB3jnFwPHkXg==", + "dependencies": { + "OpenTelemetry": "[1.17.0, 2.0.0)" + } + }, + "OpenTelemetry.Extensions.Hosting": { + "type": "Transitive", + "resolved": "1.17.0", + "contentHash": "t1OwL/4qgboGMobYVT+UV5zgWnFqCp4Pw8lcsmzh8m2K8PQsTKkyxrC32tqYTMYny3GOW4q5cltE3dTVzLmRew==", + "dependencies": { + "Microsoft.Extensions.Hosting.Abstractions": "10.0.0", + "OpenTelemetry": "1.17.0" + } + }, + "Sentry": { + "type": "Transitive", + "resolved": "6.8.0", + "contentHash": "amUjwslDtdx1p8r6z4APCxM8vHCKG4CBamPpSTwxmTMoBQ2CLwx2m3CaIttJXRT/hw9S5rNfXgjol2OqADytLQ==" + }, + "Sentry.AspNetCore": { + "type": "Transitive", + "resolved": "6.8.0", + "contentHash": "yo9TeFZPgmhyu0Vj+Zq3VxRR8kDbhlNbRAQDANN+gTwETe5uDa/H1I91PntBD7jwhWa7P218bYU+LGYOipylYA==", + "dependencies": { + "Sentry.Extensions.Logging": "6.8.0" + } + }, + "Sentry.Extensions.Logging": { + "type": "Transitive", + "resolved": "6.8.0", + "contentHash": "K7/Z7B8ec5c61ByzZOgxHxhcT+5yo7X6n7GchcaFI/X44Zn/ZsGqUFMqvypaILnc4JISAeppDTSiWdgWmflzbg==", + "dependencies": { + "Microsoft.Extensions.Configuration.Binder": "10.0.0", + "Microsoft.Extensions.Http": "10.0.0", + "Microsoft.Extensions.Logging.Configuration": "10.0.0", + "Sentry": "6.8.0" + } + }, + "SQLite": { + "type": "Transitive", + "resolved": "3.53.4", + "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" + }, + "SQLitePCLRaw.bundle_e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "SW8iASIyWMrLzqabUHYQRvALhvD4ylSBsj4PgEVGwc36kQjc9xT5kSV/XQ9rU7nIpBWD+LPyX3Hlw5FzyUzGeQ==", + "dependencies": { + "SQLite": "3.53.4", + "SQLitePCLRaw.config.e_sqlite3": "3.0.5" + } + }, + "SQLitePCLRaw.config.e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "aSk8WE5tF2MybESMgtZAEyMVCAWA0nBqOMc48HFoa9UoSdtm3goDXVzNRnefeKIwE6bV9NaNXptn1F9ReMQI0Q==", + "dependencies": { + "SQLitePCLRaw.provider.e_sqlite3": "3.0.5" + } + }, + "SQLitePCLRaw.core": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "k81AYXXRCw3Zj8rOhyBoCsx/U97KYDFI2CSKr/ijl5BwpsW/hX/4kBiDmerFaoust8nxBwa0IHQFw8MmSHRtnQ==" + }, + "SQLitePCLRaw.provider.e_sqlite3": { + "type": "Transitive", + "resolved": "3.0.5", + "contentHash": "um8YSWduhhuskTG2bHfZrBqMNQOydfU8pcseT+cu5RivOGyoUbCrGXxgoRNTmRYw2VbMWnEZVVFcneZT/5dsBg==", + "dependencies": { + "SQLitePCLRaw.core": "3.0.5" + } + }, + "System.CodeDom": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "CPc6tWO1LAer3IzfZufDBRL+UZQcj5uS207NHALQzP84Vp/z6wF0Aa0YZImOQY8iStY0A2zI/e3ihKNPfUm8XA==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "DkNjtQyPR5Ud/zHnWHdsOuKbFRL9nIC92Q76z0NmHVDoQm40toLtsGFTIWq7toBoVa6fo/DInL3PLxY3Asixyw==" + }, + "System.Management": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==", + "dependencies": { + "System.CodeDom": "6.0.0" + } + }, + "System.Numerics.Tensors": { + "type": "Transitive", + "resolved": "9.0.0", + "contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A==" + }, + "System.Security.Cryptography.Pkcs": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" + }, + "System.Security.Cryptography.Xml": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "v6/GHhLaHkuN/ISgbKzBeyC7TP7S6Qm/dVyKA+p0ay9nlJyLif+spozjAGclY/FRIv2TC+KNQCo7dSNmupvWtQ==", + "dependencies": { + "System.Security.Cryptography.Pkcs": "10.0.13" + } + }, + "System.ServiceProcess.ServiceController": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ==", + "dependencies": { + "System.Diagnostics.EventLog": "10.0.13" + } + }, + "xunit.abstractions": { + "type": "Transitive", + "resolved": "2.0.3", + "contentHash": "pot1I4YOxlWjIb5jmwvvQNbTrZ3lJQ+jUGkGjWE3hEFM0l5gOnBWS+H3qsex68s5cO52g+44vpGzhAt+42vwKg==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "1.18.0", + "contentHash": "OtFMHN8yqIcYP9wcVIgJrq01AfTxijjAqVDy/WeQVSyrDC1RzBWeQPztL49DN2syXRah8TYnfvk035s7L95EZQ==" + }, + "xunit.assert": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "/Kq28fCE7MjOV42YLVRAJzRF0WmEqsmflm0cfpMjGtzQ2lR5mYVj1/i0Y8uDAOLczkL3/jArrwehfMD0YogMAA==" + }, + "xunit.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "BiAEvqGvyme19wE0wTKdADH+NloYqikiU0mcnmiNyXaF9HyHmE6sr/3DC5vnBkgsWaE6yPyWszKSPSApWdRVeQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]", + "xunit.extensibility.execution": "[2.9.3]" + } + }, + "xunit.extensibility.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "kf3si0YTn2a8J8eZNb+zFpwfoyvIrQ7ivNk5ZYA5yuYk1bEtMe4DxJ2CF/qsRgmEnDr7MnW1mxylBaHTZ4qErA==", + "dependencies": { + "xunit.abstractions": "2.0.3" + } + }, + "xunit.extensibility.execution": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "yMb6vMESlSrE3Wfj7V6cjQ3S4TXdXpRqYeNEI3zsX31uTsGMJjEw6oD5F5u1cHnMptjhEECnmZSsPxB6ChZHDQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]" + } + }, + "heimdall.agent": { + "type": "Project", + "dependencies": { + "Heimdall.Application": "[1.0.0, )", + "Heimdall.Contracts": "[1.0.0, )", + "Heimdall.Mdns": "[1.0.0, )", + "Magick.NET-Q16-AnyCPU": "[14.16.0, )", + "Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )", + "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )", + "Microsoft.Extensions.Hosting.WindowsServices": "[10.0.13, )", + "Microsoft.ML.OnnxRuntime.Gpu": "[1.22.0, )", + "OpenTelemetry": "[1.17.0, )", + "OpenTelemetry.Exporter.Prometheus.AspNetCore": "[1.17.0-beta.1, )", + "OpenTelemetry.Extensions.Hosting": "[1.17.0, )", + "Sentry.AspNetCore": "[6.8.0, )" + } + }, + "heimdall.application": { + "type": "Project", + "dependencies": { + "AutoMapper": "[16.1.1, )", + "FluentValidation": "[11.11.0, )", + "FluentValidation.DependencyInjectionExtensions": "[11.11.0, )", + "Heimdall.Domain": "[1.0.0, )", + "MediatR": "[12.5.0, )", + "Microsoft.Data.Sqlite": "[10.0.13, )", + "Microsoft.EntityFrameworkCore": "[10.0.13, )", + "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )", + "SQLitePCLRaw.bundle_e_sqlite3": "[3.0.5, )" + } + }, + "heimdall.contracts": { + "type": "Project" + }, + "heimdall.domain": { + "type": "Project", + "dependencies": { + "Heimdall.Domain.Primitives": "[1.0.0, )" + } + }, + "heimdall.domain.primitives": { + "type": "Project" + }, + "heimdall.mdns": { + "type": "Project", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "[10.0.13, )" + } + } + } + } +} \ No newline at end of file diff --git a/todo.md b/todo.md index 2d099b7..ab21ade 100644 --- a/todo.md +++ b/todo.md @@ -48,7 +48,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. - [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. -- [ ] **GPU #77** Les Compose CPU n'exigent plus NVIDIA et n'annoncent plus un `ORT_PROVIDER=CUDA` ignoré. Des overlays optionnels exposent NVIDIA/AMD/Intel à l'inventaire; l'inférence ONNX de l'image Agent reste CPU. Restent une image/runtime GPU, la détection du fournisseur réellement attaché à la session, et les validations GPU réel + fallback CPU. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt; le test réel `RealOnnx_CpuModel_ProcessesFullHdImage` a ensuite réussi seul avec ce package. Reste à fournir/publier une image/runtime CUDA compatible, l'exposer via installation/UI, valider la recette Compose jetable et exécuter sur matériel GPU réel; aucun GPU n'est déclaré validé. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** L'édition des groupes permet maintenant de lister les caméras des sites, d'accorder/révoquer les accès de groupe et d'afficher les noms de site/caméra via l'API existante. Restent la validation produit et la vérification de l'union accès direct/groupe ainsi que des priorités dans l'interface. -- 2.54.1 From 7293342ede2044cba3d5281d436b1d8f5756b4d0 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:24:34 +0100 Subject: [PATCH 09/40] fix(agent): retry transient camera config acknowledgements --- skills/agent-runtime-acceptance/SKILL.md | 28 +++++++++++ .../Services/ConfigReceiverService.cs | 42 ++++++++++++++-- .../ConfigReceiverServiceTests.cs | 49 +++++++++++++++++++ todo.md | 2 +- 4 files changed, 115 insertions(+), 6 deletions(-) create mode 100644 skills/agent-runtime-acceptance/SKILL.md diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md new file mode 100644 index 0000000..eca9a27 --- /dev/null +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -0,0 +1,28 @@ +--- +name: agent-runtime-acceptance +description: Validate Heimdall Agent reconnect, camera configuration replacement, acknowledgement, and runtime diagnostics without camera hardware. +--- + +# Heimdall Agent runtime acceptance + +Read `AGENTS.md`, the Agent item in `todo.md`, and `skills/heimdall-dotnet/SKILL.md` before changing Agent runtime behavior. + +## Camera configuration synchronization + +- `ConfigReceiverService` fetches the complete camera settings snapshot after initial connection and reconnection; `CameraConfigStore.ReplaceCentral` validates the digest and publishes all assignments atomically. +- The Central acknowledgement is keyed to that exact digest. Retry network failures and HTTP 408/429/5xx at most three times with short bounded delays; stop on permanent 4xx responses. Do not log the API key, camera URLs, configuration payload, or response body. +- Keep the latest applied snapshot active when an acknowledgement is rejected. A later config reload/reconnect fetches and acknowledges the current snapshot again. +- Extend `ConfigReceiverServiceTests` with an in-memory HTTP handler that returns a transient failure before success. Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values. + +## Local checks + +```bash +dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode +dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore +``` + +For behavior changes, build the Agent from source in a uniquely named Docker Compose project using a private isolated network, generated credentials, loopback-only ports, and project-scoped volumes. Probe `/healthz`, then tear down that project with `down --volumes --remove-orphans` and verify its containers, volumes, and network are gone. Serialize Docker acceptance when another source build is using the shared daemon. + +## Acceptance boundary + +In-memory SignalR/HTTP fixtures and a local Agent container validate reconnect and runtime behavior without a physical camera. Mark real-camera stream stability, resource release on the deployed host, and LAN discovery as open until they pass on representative hardware and network equipment. diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index 48afd72..30385d6 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -14,6 +14,7 @@ namespace Heimdall.Agent.Services; /// public sealed class ConfigReceiverService : BackgroundService { + private const int CameraConfigAckMaxAttempts = 3; private readonly AgentState _state; private readonly AgentOptions _options; private readonly ILogger _logger; @@ -374,11 +375,10 @@ public sealed class ConfigReceiverService : BackgroundService // arrives — even if it is empty, drop the local fallback. _cameraStore.MarkCentralReceived(); - using var ack = await http.PostAsJsonAsync( - $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack", - new { version }, ct).ConfigureAwait(false); - if (!ack.IsSuccessStatusCode) - _logger.LogWarning("Camera configuration ACK was rejected: {StatusCode}", ack.StatusCode); + var acknowledged = await AcknowledgeCameraConfigurationAsync(http, version, ct).ConfigureAwait(false); + if (!acknowledged) + _logger.LogWarning("Camera configuration ACK could not be persisted after {Attempts} attempts", + CameraConfigAckMaxAttempts); } catch (Exception ex) { @@ -386,6 +386,38 @@ public sealed class ConfigReceiverService : BackgroundService } finally { _reloadLock.Release(); } } + + private async Task AcknowledgeCameraConfigurationAsync(HttpClient http, string version, CancellationToken ct) + { + var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack"; + for (var attempt = 1; attempt <= CameraConfigAckMaxAttempts; attempt++) + { + try + { + using var response = await http.PostAsJsonAsync(url, new { version }, ct).ConfigureAwait(false); + if (response.IsSuccessStatusCode) return true; + _logger.LogWarning("Camera configuration ACK attempt {Attempt} was rejected with HTTP {StatusCode}", + attempt, (int)response.StatusCode); + if (response.StatusCode is not (System.Net.HttpStatusCode.RequestTimeout or + System.Net.HttpStatusCode.TooManyRequests) && (int)response.StatusCode < 500) + return false; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + throw; + } + catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException) + { + _logger.LogWarning("Camera configuration ACK attempt {Attempt} failed ({ErrorType})", + attempt, ex.GetType().Name); + } + + if (attempt < CameraConfigAckMaxAttempts) + await Task.Delay(TimeSpan.FromMilliseconds(250 * attempt), ct).ConfigureAwait(false); + } + + return false; + } } /// diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index 4331e7a..8e65235 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.SignalR; using System.Reflection; using System.Text.Json; +using System.Net.Http.Json; using Heimdall.Agent.Services; using Heimdall.Application.DTOs; using Heimdall.Application.Security; @@ -479,6 +480,28 @@ public class ConfigReceiverServiceTests camera.Enabled.ShouldBeTrue(); } + [Fact] + public async Task FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt() + { + var cameraId = Guid.NewGuid(); + var settings = new Dictionary { [$"camera.{cameraId}.enabled"] = "true" }; + var handler = new RetryingCameraAckHandler(settings); + var factory = Substitute.For(); + factory.CreateClient("Central").Returns(_ => new HttpClient(handler, disposeHandler: false)); + var cameraStore = new CameraConfigStore(); + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "fixture-key" }; + using var service = CreateService(state, httpFactory: factory, cameraStore: cameraStore); + var fetch = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync", + BindingFlags.NonPublic | BindingFlags.Instance); + fetch.ShouldNotBeNull(); + + await (Task)fetch.Invoke(service, [CancellationToken.None])!; + + handler.AcknowledgementAttempts.ShouldBe(2); + cameraStore.Cameras.ShouldHaveSingleItem().CameraId.ShouldBe(cameraId); + cameraStore.CurrentVersion.ShouldBe(CameraConfigVersion.Compute(settings)); + } + [Fact] public void ApplySetting_CameraKey_UpdatesCameraStore() { @@ -534,6 +557,32 @@ public class ConfigReceiverServiceTests } } + private sealed class RetryingCameraAckHandler : HttpMessageHandler + { + private readonly IReadOnlyDictionary _settings; + private int _acknowledgementAttempts; + + public RetryingCameraAckHandler(IReadOnlyDictionary settings) => _settings = settings; + public int AcknowledgementAttempts => Volatile.Read(ref _acknowledgementAttempts); + + protected override Task SendAsync(HttpRequestMessage request, + CancellationToken cancellationToken) + { + if (request.Method == HttpMethod.Post) + { + var attempt = Interlocked.Increment(ref _acknowledgementAttempts); + return Task.FromResult(new HttpResponseMessage(attempt == 1 + ? System.Net.HttpStatusCode.ServiceUnavailable + : System.Net.HttpStatusCode.NoContent)); + } + + var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { Content = JsonContent.Create(_settings) }; + response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(_settings)); + return Task.FromResult(response); + } + } + /// Captures formatted log messages for assertions (in-memory, no sinks). private sealed class ListLoggerProvider : ILoggerProvider { diff --git a/todo.md b/todo.md index ab21ade..9599e49 100644 --- a/todo.md +++ b/todo.md @@ -32,7 +32,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. - [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. -- [ ] **AGENT-08** Valider reconnexion, remplacement atomique de configuration caméra et ACK persisté sur Agent déployé. +- [ ] **AGENT-08** Reconnexion, remplacement atomique du snapshot caméra et ACK exact par digest sont couverts par les fixtures SignalR/HTTP de `ConfigReceiverServiceTests`. L’ACK réessaie maintenant jusqu’à trois fois après une erreur transitoire (test 503 puis 204 : 1/1; suite Agent de référence avant ce changement : 388/388). La suite Agent passe maintenant 389/389 après ce changement; la recette Compose isolée reste à lancer quand le créneau Docker sera libre. La validation sur Agent déployé avec caméra réelle et coupure réseau reste ouverte. - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. -- 2.54.1 From 815ba7f8426e7b53b856ed57a336cc940141648a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 22:18:00 +0100 Subject: [PATCH 10/40] feat: add camera recording vertical --- docker/docker-compose.yml | 1 - skills/video-recording/SKILL.md | 18 + src/Heimdall.Agent/AgentOptions.cs | 11 + src/Heimdall.Agent/Program.cs | 1 + .../Services/AgentCameraConfig.cs | 3 +- .../Services/AgentRecordingService.cs | 315 ++ .../Services/CameraConfigStore.cs | 1 + .../CreateCamera/CreateCameraCommand.cs | 2 +- .../ToggleCameraStatusCommand.cs | 2 +- .../UpdateCamera/UpdateCameraCommand.cs | 10 +- .../GetCamera/GetCameraQueryHandler.cs | 4 +- .../GetCamerasBySite/GetCamerasBySiteQuery.cs | 2 +- .../Common/IRecordingStorage.cs | 13 + .../Common/IStorageProvider.cs | 3 + src/Heimdall.Application/DTOs/CameraDto.cs | 6 +- .../GetCamerasByGroupQuery.cs | 4 +- .../UploadRecording/UploadRecordingCommand.cs | 69 + .../GetCameraRecordingsQuery.cs | 37 + .../GetRecordingContentQuery.cs | 64 + .../Recordings/RecordingDtos.cs | 12 + .../GetEffectiveAgentConfigQuery.cs | 1 + src/Heimdall.Domain/Entities/Camera.cs | 3 + src/Heimdall.Domain/Entities/Recording.cs | 5 +- .../Configurations/CameraConfiguration.cs | 4 + .../DependencyInjection.cs | 1 + ...2743_AddCameraRecordingEnabled.Designer.cs | 2892 +++++++++++++++++ ...0261104202743_AddCameraRecordingEnabled.cs | 29 + .../Migrations/AppDbContextModelSnapshot.cs | 5 + .../Storage/AlarikStorageProvider.cs | 24 + .../Storage/BoundedReadStream.cs | 62 + .../Storage/LocalStorageProvider.cs | 15 + .../Storage/RecordingStorageAdapter.cs | 18 + .../Storage/StorageProviderFactory.cs | 36 + .../Components/Pages/CameraDetail.razor | 86 +- .../Controllers/CamerasController.cs | 2 +- .../Controllers/RecordingsController.cs | 118 + .../Localization/SharedResources.en.resx | 12 + .../Localization/SharedResources.fr.resx | 12 + .../Localization/SharedResources.resx | 12 + .../Services/HeimdallApiClient.cs | 20 +- .../AgentRecordingServiceTests.cs | 22 + .../CameraConfigStoreTests.cs | 13 + .../GetEffectiveAgentConfigHandlerTests.cs | 18 + .../LocalStorageProviderTests.cs | 25 + .../Components/Pages/CameraDetailTests.cs | 22 + .../HeimdallApiClientCoverageTests.cs | 31 + todo.md | 7 +- 47 files changed, 4051 insertions(+), 22 deletions(-) create mode 100644 skills/video-recording/SKILL.md create mode 100644 src/Heimdall.Agent/Services/AgentRecordingService.cs create mode 100644 src/Heimdall.Application/Common/IRecordingStorage.cs create mode 100644 src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs create mode 100644 src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs create mode 100644 src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs create mode 100644 src/Heimdall.Application/Recordings/RecordingDtos.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.cs create mode 100644 src/Heimdall.Infrastructure/Storage/BoundedReadStream.cs create mode 100644 src/Heimdall.Infrastructure/Storage/RecordingStorageAdapter.cs create mode 100644 src/Heimdall.Web/Controllers/RecordingsController.cs create mode 100644 tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 8a16920..2435dda 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -61,5 +61,4 @@ volumes: networks: heimdall-net: - name: heimdall-net driver: bridge diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md new file mode 100644 index 0000000..f8a5ad5 --- /dev/null +++ b/skills/video-recording/SKILL.md @@ -0,0 +1,18 @@ +--- +name: video-recording +description: Implement and validate Heimdall Agent video segments, central recording storage, access checks, ranges, and retention. +--- + +# Heimdall video recording + +Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses. + +- Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries. +- Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port. +- Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback. +- The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL. +- Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance. +- Add PostgreSQL tests for migration, metadata/idempotency, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. +- For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. + +Current product gaps are audio/event-trigger capture, an explicit Central storage quota, and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index eda76cf..98eab52 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -51,6 +51,17 @@ public sealed class AgentOptions /// Directory for persisting agent identity state. Defaults to /var/lib/heimdall on Linux. public string? StateDirectory { get; init; } + /// Length of completed MP4 segments created for recording-enabled cameras. + [Range(5, 300)] + public int RecordingSegmentSeconds { get; init; } = 60; + + /// Upper bound for queued completed recordings kept locally while Central is unavailable. + [Range(typeof(long), "16777216", "107374182400")] + public long RecordingSpoolMaxBytes { get; init; } = 1_073_741_824; + + /// FFmpeg executable used for opt-in segment recording. + public string RecordingFfmpegPath { get; init; } = "ffmpeg"; + /// Max retries for agent registration (default: 5). [Range(1, 20)] public int RegistrationMaxRetries { get; init; } = 5; diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 61c6d94..1ceb708 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -171,6 +171,7 @@ builder.Services.AddSingleton(sp => new SnapshotPipelineService(new SnapshotPipe sp.GetRequiredService(), sp.GetRequiredService()))); builder.Services.AddHostedService(sp => sp.GetRequiredService()); +builder.Services.AddHostedService(); // Log capture & upload to Central (ticket #50) builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs index e2fb29b..0603193 100644 --- a/src/Heimdall.Agent/Services/AgentCameraConfig.cs +++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs @@ -11,7 +11,8 @@ public sealed record AgentCameraConfig( string RtspUrl, string? SubRtspUrl, bool Enabled, - Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null) + Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null, + bool RecordingEnabled = false) { /// /// URL used for AI capture: the low-res sub-stream when available, diff --git a/src/Heimdall.Agent/Services/AgentRecordingService.cs b/src/Heimdall.Agent/Services/AgentRecordingService.cs new file mode 100644 index 0000000..647c910 --- /dev/null +++ b/src/Heimdall.Agent/Services/AgentRecordingService.cs @@ -0,0 +1,315 @@ +using System.Diagnostics; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Heimdall.Agent.Services; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent; + +/// +/// Starts an opt-in FFmpeg segment process for enabled cameras, persists completed +/// segments under the Agent state volume, and retries uploads until Central acknowledges them. +/// +public sealed class AgentRecordingService : BackgroundService +{ + private const long MaxSegmentBytes = 100 * 1024 * 1024; + private static readonly TimeSpan LoopDelay = TimeSpan.FromSeconds(5); + private readonly CameraConfigStore _cameras; + private readonly CameraStreamService _streams; + private readonly AgentState _state; + private readonly AgentOptions _options; + private readonly IHttpClientFactory _clients; + private readonly ILogger _logger; + private readonly Dictionary _sessions = []; + private readonly SemaphoreSlim _lifecycle = new(1, 1); + private string _spoolRoot = string.Empty; + + public AgentRecordingService(CameraConfigStore cameras, CameraStreamService streams, AgentState state, + IOptions options, IHttpClientFactory clients, ILogger logger) + { + _cameras = cameras; + _streams = streams; + _state = state; + _options = options.Value; + _clients = clients; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var stateDirectory = _options.StateDirectory ?? + (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); + _spoolRoot = Path.GetFullPath(Path.Combine(stateDirectory, "recordings")); + Directory.CreateDirectory(_spoolRoot); + if (OperatingSystem.IsLinux()) + File.SetUnixFileMode(_spoolRoot, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + + try + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await ReconcileAsync(stoppingToken).ConfigureAwait(false); + await UploadCompletedSegmentsAsync(stoppingToken).ConfigureAwait(false); + await TrimSpoolAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + catch (Exception ex) + { + _logger.LogWarning("Recording loop failed (error type {ErrorType})", ex.GetType().Name); + } + await Task.Delay(LoopDelay, stoppingToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } + finally + { + foreach (var cameraId in _sessions.Keys.ToArray()) + await StopSessionAsync(cameraId, CancellationToken.None).ConfigureAwait(false); + } + } + + private async Task ReconcileAsync(CancellationToken ct) + { + await _lifecycle.WaitAsync(ct).ConfigureAwait(false); + try + { + var configured = _cameras.Cameras.ToDictionary(c => c.CameraId); + foreach (var (cameraId, session) in _sessions.ToArray()) + { + if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled || !camera.RecordingEnabled || + camera.RtspUrl != session.RtspUrl || !_streams.IsStreamActive(cameraId) || session.Process.HasExited) + await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false); + } + + foreach (var camera in configured.Values.Where(c => c.Enabled && c.RecordingEnabled && + !string.IsNullOrWhiteSpace(c.RtspUrl))) + { + if (_streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId)) + StartSession(camera); + } + } + finally { _lifecycle.Release(); } + } + + private void StartSession(AgentCameraConfig camera) + { + var cameraRoot = Path.Combine(_spoolRoot, camera.CameraId.ToString("N")); + var sessionDirectory = Path.Combine(cameraRoot, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(sessionDirectory); + if (OperatingSystem.IsLinux()) + File.SetUnixFileMode(sessionDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + var startedAt = DateTime.UtcNow; + File.WriteAllText(Path.Combine(sessionDirectory, "started-at.txt"), startedAt.ToString("O", CultureInfo.InvariantCulture)); + var startInfo = CreateStartInfo(_options.RecordingFfmpegPath, camera.RtspUrl!, sessionDirectory, + _options.RecordingSegmentSeconds); + Process? process = null; + try + { + process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }; + if (!process.Start()) throw new InvalidOperationException("FFmpeg did not start"); + var session = new RecordingSession(camera.CameraId, camera.RtspUrl!, sessionDirectory, startedAt, process); + _sessions[camera.CameraId] = session; + session.ErrorDrain = DrainStandardErrorAsync(process); + _logger.LogInformation("Video recording started for camera {CameraId}", camera.CameraId); + } + catch (Exception ex) + { + process?.Dispose(); + _logger.LogWarning("Video recording could not start for camera {CameraId} (error type {ErrorType})", + camera.CameraId, ex.GetType().Name); + } + } + + internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string rtspUrl, string sessionDirectory, + int segmentSeconds) + { + var info = new ProcessStartInfo + { + FileName = ffmpegPath, + RedirectStandardInput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var argument in new[] + { + "-hide_banner", "-loglevel", "error", "-rtsp_transport", "tcp", "-i", rtspUrl, + "-map", "0:v:0", "-c:v", "copy", "-f", "segment", "-segment_time", + segmentSeconds.ToString(CultureInfo.InvariantCulture), "-segment_format", "mp4", + "-reset_timestamps", "1", "-segment_list", Path.Combine(sessionDirectory, "segments.csv"), + "-segment_list_type", "csv", "-segment_list_size", "10000", + Path.Combine(sessionDirectory, "segment-%06d.mp4") + }) info.ArgumentList.Add(argument); + return info; + } + + private static async Task DrainStandardErrorAsync(Process process) + { + try + { + while (await process.StandardError.ReadLineAsync().ConfigureAwait(false) is not null) { } + } + catch (IOException) { } + catch (ObjectDisposedException) { } + } + + private async Task StopSessionAsync(Guid cameraId, CancellationToken ct) + { + await _lifecycle.WaitAsync(ct).ConfigureAwait(false); + try + { + if (_sessions.TryGetValue(cameraId, out var session)) + await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false); + } + finally { _lifecycle.Release(); } + } + + private async Task StopSessionCoreAsync(Guid cameraId, RecordingSession session, CancellationToken ct) + { + _sessions.Remove(cameraId); + try + { + if (!session.Process.HasExited) + { + try { await session.Process.StandardInput.WriteLineAsync("q").ConfigureAwait(false); } + catch (IOException) { } + try { await session.Process.WaitForExitAsync(ct).WaitAsync(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); } + catch (TimeoutException) { session.Process.Kill(entireProcessTree: true); } + catch (InvalidOperationException) { } + } + if (session.ErrorDrain is not null) await session.ErrorDrain.ConfigureAwait(false); + _logger.LogInformation("Video recording stopped for camera {CameraId}", cameraId); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) + { + _logger.LogDebug("FFmpeg cleanup failed for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); + } + finally { session.Process.Dispose(); } + } + + private async Task UploadCompletedSegmentsAsync(CancellationToken ct) + { + if (!Directory.Exists(_spoolRoot)) return; + foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories)) + { + ct.ThrowIfCancellationRequested(); + if (!Guid.TryParseExact(Directory.GetParent(Directory.GetParent(manifest)!.FullName)!.Name, "N", out var cameraId)) + continue; + DateTime startedAt; + try + { + startedAt = DateTime.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(manifest)!, "started-at.txt")), + CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind).ToUniversalTime(); + } + catch (IOException) { continue; } + catch (FormatException) { continue; } + string[] rows; + try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); } + catch (IOException) { continue; } + foreach (var row in rows) + { + var fields = row.Split(','); + if (fields.Length < 3) continue; + var fileName = Path.GetFileName(fields[0]); + if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal) || + !double.TryParse(fields[1], CultureInfo.InvariantCulture, out var startSeconds) || + !double.TryParse(fields[2], CultureInfo.InvariantCulture, out var endSeconds)) continue; + var duration = endSeconds - startSeconds; + if (duration is < 1 or > 300 || !double.IsFinite(duration) || !double.IsFinite(startSeconds)) continue; + var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName); + if (!File.Exists(path)) continue; + var info = new FileInfo(path); + if (info.Length > MaxSegmentBytes) + { + _logger.LogWarning("Dropping oversized video segment for camera {CameraId} ({SizeBytes} bytes)", cameraId, info.Length); + info.Delete(); + continue; + } + await UploadSegmentAsync(cameraId, path, startedAt.AddSeconds(startSeconds), duration, ct).ConfigureAwait(false); + } + } + } + + private async Task UploadSegmentAsync(Guid cameraId, string path, DateTime timestamp, double duration, CancellationToken ct) + { + var relativePath = Path.GetRelativePath(_spoolRoot, path).Replace(Path.DirectorySeparatorChar, '/'); + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(relativePath)); + var recordingId = new Guid(hash.AsSpan(0, 16)); + var url = $"api/cameras/{cameraId:D}/recordings/{recordingId:D}/content?timestamp={Uri.EscapeDataString(timestamp.ToString("O", CultureInfo.InvariantCulture))}&durationSeconds={duration.ToString(CultureInfo.InvariantCulture)}"; + try + { + using var request = new HttpRequestMessage(HttpMethod.Put, url); + request.Headers.Add("X-API-Key", _state.ApiKey); + await using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, + 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan); + request.Content = new StreamContent(input); + request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"); + request.Content.Headers.ContentLength = input.Length; + using var response = await _clients.CreateClient("Central").SendAsync(request, + HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + _logger.LogWarning("Video segment upload returned HTTP {StatusCode} for camera {CameraId}", + (int)response.StatusCode, cameraId); + return; + } + input.Close(); + File.Delete(path); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (HttpRequestException ex) + { + _logger.LogWarning("Video segment upload failed for camera {CameraId} (error type {ErrorType})", + cameraId, ex.GetType().Name); + } + catch (IOException ex) + { + _logger.LogWarning("Video segment could not be read or removed for camera {CameraId} (error type {ErrorType})", + cameraId, ex.GetType().Name); + } + } + + private async Task TrimSpoolAsync(CancellationToken ct) + { + var ready = new List(); + foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories)) + { + string[] rows; + try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); } + catch (IOException) { continue; } + foreach (var row in rows) + { + var fileName = Path.GetFileName(row.Split(',')[0]); + if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal)) continue; + var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName); + if (File.Exists(path)) ready.Add(new FileInfo(path)); + } + } + var total = ready.Sum(file => file.Length); + foreach (var file in ready.OrderBy(file => file.LastWriteTimeUtc)) + { + if (total <= _options.RecordingSpoolMaxBytes) break; + ct.ThrowIfCancellationRequested(); + var size = file.Length; + try + { + file.Delete(); + total -= size; + _logger.LogWarning("Dropping oldest queued video segment for camera {CameraId}; local recording spool reached its configured limit", + Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(file.FullName)))); + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + + private sealed record RecordingSession(Guid CameraId, string RtspUrl, string Directory, + DateTime StartedAt, Process Process) + { + public Task? ErrorDrain { get; set; } + } +} diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs index 3913e87..fb94add 100644 --- a/src/Heimdall.Agent/Services/CameraConfigStore.cs +++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs @@ -102,6 +102,7 @@ public sealed class CameraConfigStore "rtsp" => existing with { RtspUrl = value }, "sub_rtsp" => existing with { SubRtspUrl = value }, "enabled" => existing with { Enabled = ParseBool(value) }, + "recording_enabled" => existing with { RecordingEnabled = ParseBool(value) }, "profile" => existing with { DetectionProfile = ParseProfile(value) }, _ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field)) }; diff --git a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs index e0779d5..30f1abc 100644 --- a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs @@ -53,5 +53,5 @@ public class CreateCameraCommandHandler : IRequestHandler>; + Guid? ActorId = null, + bool? RecordingEnabled = null) : IRequest>; public class UpdateCameraCommandHandler : IRequestHandler> { @@ -48,11 +49,14 @@ public class UpdateCameraCommandHandler : IRequestHandlerStorage operations for recording media, bound to the captured destination. +public interface IRecordingStorage +{ + StorageLocation CaptureCurrentLocation(); + Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, CancellationToken ct = default); + Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default); + Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, + CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Common/IStorageProvider.cs b/src/Heimdall.Application/Common/IStorageProvider.cs index b413c94..b13b8fc 100644 --- a/src/Heimdall.Application/Common/IStorageProvider.cs +++ b/src/Heimdall.Application/Common/IStorageProvider.cs @@ -20,6 +20,9 @@ public interface IStorageProvider /// Open a stream for reading a stored object. Null when missing. Task DownloadAsync(string key, CancellationToken ct = default); + /// Open a single inclusive byte range without downloading the rest of the object. + Task DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default); + /// Delete a single object. No-op when missing. Task DeleteAsync(string key, CancellationToken ct = default); diff --git a/src/Heimdall.Application/DTOs/CameraDto.cs b/src/Heimdall.Application/DTOs/CameraDto.cs index 46bbc52..9e980a0 100644 --- a/src/Heimdall.Application/DTOs/CameraDto.cs +++ b/src/Heimdall.Application/DTOs/CameraDto.cs @@ -15,7 +15,8 @@ public record UpdateCameraRequest( CameraStatus? Status, string? Manufacturer = null, string? Model = null, - DetectionProfileDto? DetectionProfile = null); + DetectionProfileDto? DetectionProfile = null, + bool? RecordingEnabled = null); /// Camera response including all discovery and stream test metadata. public record CameraResponse( @@ -45,4 +46,5 @@ public record CameraResponse( bool HasPtz, bool HasAudio, bool HasMotionDetection, - DateTime CreatedAt); + DateTime CreatedAt, + bool RecordingEnabled = false); diff --git a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs index 754b47e..92f12bd 100644 --- a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs +++ b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs @@ -45,10 +45,10 @@ public class GetCamerasByGroupHandler : IRequestHandler>.Success( new PagedResult(items, total, request.Page, request.PageSize)); } -} \ No newline at end of file +} diff --git a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs new file mode 100644 index 0000000..afc8fc5 --- /dev/null +++ b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs @@ -0,0 +1,69 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Recordings; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Recordings.Commands.UploadRecording; + +public sealed record UploadRecordingCommand( + Guid AgentId, + Guid CameraId, + Guid RecordingId, + DateTime Timestamp, + double DurationSeconds, + long SizeBytes, + Stream Content) : IRequest>; + +public sealed class UploadRecordingHandler( + IApplicationDbContext db, + IRecordingStorage storage) : IRequestHandler> +{ + public async Task> Handle(UploadRecordingCommand request, CancellationToken ct) + { + if (request.AgentId == Guid.Empty || request.CameraId == Guid.Empty || request.RecordingId == Guid.Empty || + request.DurationSeconds is < 1 or > 300 || !double.IsFinite(request.DurationSeconds) || + request.SizeBytes is < 12 or > 100 * 1024 * 1024 || request.Content.CanSeek && request.Content.Length != request.SizeBytes) + return ServiceResult.Failure("Invalid recording segment metadata", 400); + + var camera = await db.Cameras.AsNoTracking() + .Where(c => c.Id == request.CameraId && !c.IsDeleted) + .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (camera?.AgentId != request.AgentId) + return ServiceResult.NotFound("Camera not found"); + + var existing = await db.Recordings.AsNoTracking() + .Where(r => r.Id == request.RecordingId) + .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (existing is not null) + return existing.CameraId == request.CameraId + ? ServiceResult.Success(Map(existing.Id, existing.CameraId, existing.Timestamp, existing.DurationSeconds, existing.SizeBytes)) + : ServiceResult.Conflict("Recording identifier already belongs to another camera"); + + var timestamp = CameraEvent.NormalizeOccurredAt(request.Timestamp); + var location = storage.CaptureCurrentLocation(); + var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}.mp4"; + if (request.Content.CanSeek) request.Content.Position = 0; + await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false); + + var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds, + key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId); + db.Recordings.Add(recording); + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + + var end = timestamp.AddSeconds(request.DurationSeconds); + await db.CameraEvents + .Where(e => e.CameraId == request.CameraId && e.RecordingId == null && e.OccurredAt >= timestamp && e.OccurredAt < end) + .ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct) + .ConfigureAwait(false); + + return ServiceResult.Success(Map(recording.Id, recording.CameraId, + recording.Timestamp, recording.DurationSeconds, recording.SizeBytes)); + } + + private static RecordingDto Map(Guid id, Guid cameraId, DateTime timestamp, double duration, long size) => + new(id, cameraId, timestamp, duration, size, $"/api/recordings/{id:D}/content"); +} diff --git a/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs b/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs new file mode 100644 index 0000000..20a4c74 --- /dev/null +++ b/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs @@ -0,0 +1,37 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Recordings; +using Heimdall.Application.Services; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Recordings.Queries.GetCameraRecordings; + +public sealed record GetCameraRecordingsQuery(Guid CameraId, Guid UserId, DateTime? From, DateTime? To, int Page, int PageSize) + : IRequest>>; + +public sealed class GetCameraRecordingsHandler( + IApplicationDbContext db, + ICameraAccessService access) : IRequestHandler>> +{ + public async Task>> Handle(GetCameraRecordingsQuery request, CancellationToken ct) + { + if (request.Page < 1 || request.PageSize is < 1 or > 100 || + request.From.HasValue && request.To.HasValue && request.From >= request.To) + return ServiceResult>.Failure("Invalid recording page or time range", 400); + if (!await access.HasCameraAccessAsync(request.UserId, request.CameraId, ct).ConfigureAwait(false)) + return ServiceResult>.NotFound("Camera not found"); + + var query = db.Recordings.AsNoTracking().Where(r => r.CameraId == request.CameraId); + if (request.From is DateTime from) query = query.Where(r => r.Timestamp >= from); + if (request.To is DateTime to) query = query.Where(r => r.Timestamp < to); + var total = await query.CountAsync(ct).ConfigureAwait(false); + var rows = await query.OrderByDescending(r => r.Timestamp) + .Skip((request.Page - 1) * request.PageSize).Take(request.PageSize) + .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes }) + .ToListAsync(ct).ConfigureAwait(false); + var items = rows.Select(r => new RecordingDto(r.Id, r.CameraId, r.Timestamp, + r.DurationSeconds, r.SizeBytes, $"/api/recordings/{r.Id:D}/content")).ToArray(); + return ServiceResult>.Success(new(items, total, request.Page, request.PageSize)); + } +} diff --git a/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs b/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs new file mode 100644 index 0000000..fd557b8 --- /dev/null +++ b/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs @@ -0,0 +1,64 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Recordings; +using Heimdall.Application.Services; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Recordings.Queries.GetRecordingContent; + +public sealed record GetRecordingContentQuery(Guid RecordingId, Guid UserId, + long? RangeStart = null, long? RangeEnd = null, long? SuffixLength = null) + : IRequest>; + +public sealed class GetRecordingContentHandler( + IApplicationDbContext db, + ICameraAccessService access, + IRecordingStorage storage) : IRequestHandler> +{ + public async Task> Handle(GetRecordingContentQuery request, CancellationToken ct) + { + var recording = await db.Recordings.AsNoTracking() + .Where(r => r.Id == request.RecordingId) + .Select(r => new + { + r.CameraId, r.StoragePath, r.SizeBytes, r.StorageProvider, + r.StorageRoot, r.StorageEndpoint, r.StorageBucket, r.StorageLocationCaptured + }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (recording is null || !recording.StorageLocationCaptured || + !await access.HasCameraAccessAsync(request.UserId, recording.CameraId, ct).ConfigureAwait(false)) + return ServiceResult.NotFound("Recording not found"); + + var location = new Heimdall.Domain.Entities.StorageLocation(recording.StorageProvider, + recording.StorageRoot, recording.StorageEndpoint, recording.StorageBucket); + if (!location.IsComplete) + return ServiceResult.NotFound("Recording not found"); + if (request.SuffixLength is <= 0 || request.RangeStart is < 0 || request.RangeEnd is < 0 || + request.RangeStart.HasValue && request.SuffixLength.HasValue) + return ServiceResult.Failure("Invalid byte range", 416); + + var isPartial = request.RangeStart.HasValue || request.SuffixLength.HasValue; + var start = request.SuffixLength is long suffix + ? Math.Max(0, recording.SizeBytes - suffix) + : request.RangeStart ?? 0; + var end = Math.Min(request.RangeEnd ?? recording.SizeBytes - 1, recording.SizeBytes - 1); + if (isPartial && (start >= recording.SizeBytes || end < start)) + return ServiceResult.Failure("Byte range is not satisfiable", 416); + + Stream? stream; + try + { + stream = isPartial + ? await storage.DownloadRangeAsync(recording.StoragePath, location, start, end, ct).ConfigureAwait(false) + : await storage.DownloadAsync(recording.StoragePath, location, ct).ConfigureAwait(false); + } + catch (ArgumentOutOfRangeException) + { + return ServiceResult.Failure("Byte range is not satisfiable", 416); + } + return stream is null + ? ServiceResult.NotFound("Recording content not found") + : ServiceResult.Success(new(stream, recording.SizeBytes, start, + isPartial ? end - start + 1 : recording.SizeBytes, isPartial, "video/mp4")); + } +} diff --git a/src/Heimdall.Application/Recordings/RecordingDtos.cs b/src/Heimdall.Application/Recordings/RecordingDtos.cs new file mode 100644 index 0000000..fd61d7c --- /dev/null +++ b/src/Heimdall.Application/Recordings/RecordingDtos.cs @@ -0,0 +1,12 @@ +namespace Heimdall.Application.Recordings; + +public sealed record RecordingDto( + Guid Id, + Guid CameraId, + DateTime Timestamp, + double DurationSeconds, + long SizeBytes, + string ContentUrl); + +public sealed record RecordingContent(Stream Stream, long SizeBytes, long Offset, long ContentLength, + bool IsPartial, string ContentType); diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index db7e3fb..5b97fd2 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -121,6 +121,7 @@ public class GetEffectiveAgentConfigQueryHandler if (!string.IsNullOrWhiteSpace(camera.SubRtspUrl)) config[$"{prefix}.sub_rtsp"] = camera.SubRtspUrl; config[$"{prefix}.enabled"] = camera.Status != CameraStatus.Disabled ? "true" : "false"; + config[$"{prefix}.recording_enabled"] = camera.RecordingEnabled ? "true" : "false"; } return ServiceResult>.Success(config); diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs index 2dce07c..fac65dd 100644 --- a/src/Heimdall.Domain/Entities/Camera.cs +++ b/src/Heimdall.Domain/Entities/Camera.cs @@ -13,6 +13,8 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable public string? Model { get; private set; } public string? RtspUrl { get; private set; } public CameraStatus Status { get; private set; } = CameraStatus.Disabled; + /// Whether the assigned Agent stores bounded video segments for this camera. + public bool RecordingEnabled { get; private set; } // ── Discovery ─────────────────────────────────────────────────── /// How this camera was discovered (manual, ONVIF, mDNS, etc.). @@ -111,6 +113,7 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable } public void SetStatus(CameraStatus status) => Status = status; + public void SetRecordingEnabled(bool enabled) => RecordingEnabled = enabled; public void SetCapabilities(bool ptz, bool audio, bool motion) { diff --git a/src/Heimdall.Domain/Entities/Recording.cs b/src/Heimdall.Domain/Entities/Recording.cs index e6bc01d..fe7aff9 100644 --- a/src/Heimdall.Domain/Entities/Recording.cs +++ b/src/Heimdall.Domain/Entities/Recording.cs @@ -37,8 +37,9 @@ public class Recording : Entity, IAuditableEntity long sizeBytes, StorageProvider storageProvider, StorageLocation storageLocation, - Guid? storagePolicyId = null) - : base(Guid.NewGuid()) + Guid? storagePolicyId = null, + Guid? id = null) + : base(id ?? Guid.NewGuid()) { CameraId = cameraId; Timestamp = timestamp; diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs index 7ac1afe..9648181 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs @@ -35,6 +35,10 @@ public class CameraConfiguration : IEntityTypeConfiguration .IsRequired() .IsUnicode(false); + builder.Property(c => c.RecordingEnabled) + .HasDefaultValue(false) + .IsRequired(); + // ── Discovery ─────────────────────────────────────────────── builder.Property(c => c.DiscoveryMethod) .HasConversion() diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 64f5af7..6973e32 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -52,6 +52,7 @@ public static class DependencyInjection services.AddSingleton(); services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); + services.AddScoped(); // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() diff --git a/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs new file mode 100644 index 0000000..8fae6a1 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs @@ -0,0 +1,2892 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261104202743_AddCameraRecordingEnabled")] + partial class AddCameraRecordingEnabled + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuLoadPercent") + .HasColumnType("double precision"); + + b.Property("GpuName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + b.Property("LastAppliedCameraConfigAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedCameraConfigVersion") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("VramMb") + .HasColumnType("bigint"); + + b.Property("VramUsageBytes") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CapturedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuTemperatureCelsius") + .HasColumnType("double precision"); + + b.Property("GpuUtilizationPercent") + .HasColumnType("double precision"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CapturedAtUtc"); + + b.HasIndex("AgentId", "CapturedAtUtc") + .IsUnique(); + + b.HasIndex("SiteId", "CapturedAtUtc"); + + b.ToTable("agent_metric_samples", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssignedAgentId") + .HasColumnType("uuid"); + + b.Property("AttemptId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DispatchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("JobType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MaxExecutionTime") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(3000000000L); + + b.Property("MaxRetries") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(3); + + b.Property("ParametersJson") + .HasColumnType("jsonb"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("RequiredCpuCores") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("RequiredMemoryMb") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L); + + b.Property("RequiresGpu") + .HasColumnType("boolean"); + + b.Property("ResultJson") + .HasColumnType("jsonb"); + + b.Property("RetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId") + .HasDatabaseName("ix_analysis_jobs_camera"); + + b.HasIndex("AssignedAgentId", "Status") + .HasDatabaseName("ix_analysis_jobs_agent_workload") + .HasFilter("\"AssignedAgentId\" IS NOT NULL"); + + b.HasIndex("Status", "DispatchedAt") + .HasDatabaseName("ix_analysis_jobs_timeout"); + + b.HasIndex("Status", "Priority", "CreatedAt") + .HasDatabaseName("ix_analysis_jobs_pending"); + + b.ToTable("analysis_jobs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.HasIndex("StoragePolicyId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("ExecutionProfileJson") + .HasColumnType("text"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitCategory") + .HasColumnType("integer"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitIsPaired") + .HasColumnType("boolean"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitPort") + .HasColumnType("integer"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("SnapshotStorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageProvider") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SnapshotStorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id", "OccurredAt"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("MetadataJson"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("MetadataJson"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("MetadataJson"), new[] { "jsonb_path_ops" }); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.HasIndex("PersonId", "OccurredAt"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Consumed") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Verifying") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserId"); + + b.ToTable("login_challenges", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FailureReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("CameraId", "CreatedAt"); + + b.ToTable("manual_snapshot_requests", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeliveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastErrorType") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("LeaseExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NotificationId") + .HasColumnType("uuid"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)"); + + b.Property("ServiceUrl") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("NotificationId", "Channel") + .IsUnique() + .HasDatabaseName("ux_notification_deliveries_notification_channel"); + + b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt") + .HasDatabaseName("ix_notification_deliveries_dispatch"); + + b.ToTable("notification_deliveries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("StorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StorageLocationCaptured") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AutoUpdateEnabled") + .HasColumnType("boolean"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FirstSeenAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LocalRoot") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("S3Bucket") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("character varying(256)"); + + b.Property("S3Endpoint") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("Provider") + .HasDatabaseName("ix_storage_destinations_provider"); + + b.ToTable("storage_destinations", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("UserId"); + + b.ToTable("user_cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId", "SiteId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.ToTable("UserCameraAccesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", null) + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "AssignedAgent") + .WithMany() + .HasForeignKey("AssignedAgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedAgent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.HasOne("Heimdall.Domain.Entities.Notification", null) + .WithMany() + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("GroupCameraAccesses"); + + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.cs b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.cs new file mode 100644 index 0000000..1ab95dd --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddCameraRecordingEnabled : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RecordingEnabled", + table: "cameras", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "RecordingEnabled", + table: "cameras"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 5a48432..86407ed 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -719,6 +719,11 @@ namespace Heimdall.Infrastructure.Migrations b.Property("OnvifPort") .HasColumnType("integer"); + b.Property("RecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + b.Property("RtspPort") .HasColumnType("integer"); diff --git a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs index 73021e7..cbb76d5 100644 --- a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs @@ -115,6 +115,30 @@ public sealed class AlarikStorageProvider : IStorageProvider, IDisposable } } + public async Task DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default) + { + if (_client is null) return null; + if (start < 0 || endInclusive < start) throw new ArgumentOutOfRangeException(nameof(start)); + try + { + var response = await _client.GetObjectAsync(new GetObjectRequest + { + BucketName = _bucket, + Key = key, + ByteRange = new ByteRange(start, endInclusive), + }, ct).ConfigureAwait(false); + return response.ResponseStream; + } + catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) + { + return null; + } + catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.RequestedRangeNotSatisfiable) + { + throw new ArgumentOutOfRangeException(nameof(endInclusive)); + } + } + public async Task DeleteAsync(string key, CancellationToken ct = default) { if (_client is null) diff --git a/src/Heimdall.Infrastructure/Storage/BoundedReadStream.cs b/src/Heimdall.Infrastructure/Storage/BoundedReadStream.cs new file mode 100644 index 0000000..0c2b842 --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/BoundedReadStream.cs @@ -0,0 +1,62 @@ +namespace Heimdall.Infrastructure.Storage; + +/// Limits a provider stream to an inclusive storage byte range. +internal sealed class BoundedReadStream : Stream +{ + private readonly Stream inner; + private readonly long length; + private long remaining; + + public BoundedReadStream(Stream inner, long length) + { + this.inner = inner; + this.length = length; + remaining = length; + } + public override bool CanRead => inner.CanRead; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => length; + public override long Position { get => Length - remaining; set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + { + if (remaining == 0) return 0; + var read = inner.Read(buffer, offset, (int)Math.Min(count, remaining)); + remaining -= read; + return read; + } + public override int Read(Span buffer) + { + if (remaining == 0) return 0; + var read = inner.Read(buffer[..(int)Math.Min(buffer.Length, remaining)]); + remaining -= read; + return read; + } + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (remaining == 0) return 0; + var read = await inner.ReadAsync(buffer[..(int)Math.Min(buffer.Length, remaining)], cancellationToken).ConfigureAwait(false); + remaining -= read; + return read; + } + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadArrayAsync(buffer, offset, count, cancellationToken); + + private Task ReadArrayAsync(byte[] buffer, int offset, int count, CancellationToken ct) => + ReadAsync(buffer.AsMemory(offset, count), ct).AsTask(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + protected override void Dispose(bool disposing) + { + if (disposing) inner.Dispose(); + base.Dispose(disposing); + } + public override async ValueTask DisposeAsync() + { + await inner.DisposeAsync().ConfigureAwait(false); + await base.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs index 23f7a53..1018a65 100644 --- a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs @@ -90,6 +90,21 @@ public sealed class LocalStorageProvider : IStorageProvider return Task.FromResult(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 64 * 1024, useAsync: true)); } + public Task DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default) + { + if (start < 0 || endInclusive < start) throw new ArgumentOutOfRangeException(nameof(start)); + var path = ResolvePath(key); + if (!File.Exists(path)) return Task.FromResult(null); + var inner = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 64 * 1024, useAsync: true); + if (endInclusive >= inner.Length) + { + inner.Dispose(); + throw new ArgumentOutOfRangeException(nameof(endInclusive)); + } + inner.Position = start; + return Task.FromResult(new BoundedReadStream(inner, endInclusive - start + 1)); + } + public Task DeleteAsync(string key, CancellationToken ct = default) { var path = ResolvePath(key); diff --git a/src/Heimdall.Infrastructure/Storage/RecordingStorageAdapter.cs b/src/Heimdall.Infrastructure/Storage/RecordingStorageAdapter.cs new file mode 100644 index 0000000..613e35d --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/RecordingStorageAdapter.cs @@ -0,0 +1,18 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; + +namespace Heimdall.Infrastructure.Storage; + +public sealed class RecordingStorageAdapter(StorageProviderFactory storage) : IRecordingStorage +{ + public StorageLocation CaptureCurrentLocation() => storage.CaptureCurrentLocation(); + + public Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, + CancellationToken ct = default) => storage.UploadAsync(key, content, contentType, location, ct); + + public Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default) => + storage.DownloadAsync(key, location, ct); + + public Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, + CancellationToken ct = default) => storage.DownloadRangeAsync(key, location, start, endInclusive, ct); +} diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs index 10eab97..1f59e90 100644 --- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -183,6 +183,42 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat } } + public async Task DownloadRangeAsync( + string key, + long start, + long endInclusive, + CancellationToken ct = default) + { + var location = CaptureCurrentLocation(); + return await DownloadRangeAsync(key, location, start, endInclusive, ct).ConfigureAwait(false); + } + + public async Task DownloadRangeAsync( + string key, + Heimdall.Domain.Entities.StorageLocation location, + long start, + long endInclusive, + CancellationToken ct = default) + { + if (start < 0 || endInclusive < start) throw new ArgumentOutOfRangeException(nameof(start)); + var provider = Resolve(location); + try + { + var stream = await provider.DownloadRangeAsync(key, start, endInclusive, ct).ConfigureAwait(false); + if (stream is null) + { + DisposeProvider(provider); + return null; + } + return new ProviderOwnedStream(stream, provider as IDisposable); + } + catch + { + DisposeProvider(provider); + throw; + } + } + public async Task DeleteAsync(string key, CancellationToken ct = default) { var provider = Resolve(); diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 43f3fb1..17d320e 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -99,6 +99,11 @@ else @Text["CameraDetail_Model"] @(_camera.Model ?? "-") + + + @Text["CameraDetail_RecordingHelp"] + @if (!string.IsNullOrEmpty(_editError)) @@ -132,6 +137,57 @@ else + @* ─── Enregistrements: les URL same-origin héritent de l'authentification du navigateur et supportent Range. ─── *@ + + @Text["CameraDetail_Recordings"] + + @if (_recordingsLoading) + { + + + + } + else if (_recordings.Count > 0) + { + @if (_selectedRecording is not null) + { + + + } + + + @Text["CameraDetail_Timestamp"] + @Text["CameraDetail_Duration"] + @Text["CameraDetail_Size"] + + + + @context.Timestamp.ToLocalTime().ToString("g", Language.Culture) + @FormatRecordingDuration(context.DurationSeconds) + @FormatRecordingSize(context.SizeBytes) + + + @Text["CameraDetail_PlayRecording"] + + + + + } + else + { + @Text["CameraDetail_NoRecordings"] + } + @* ─── Mini-timeline : événements récents ─── *@ @Text["CameraDetail_RecentEvents"] @@ -210,6 +266,7 @@ else private CameraItem? _camera; private string _editName = ""; private string? _editRtspUrl; + private bool _recordingEnabled; private string _editError = ""; private string _editSuccess = ""; private bool _loading = true; @@ -219,6 +276,9 @@ else private bool _confirmDeleteShow; private List? _events; + private List _recordings = []; + private RecordingItem? _selectedRecording; + private bool _recordingsLoading; private bool _eventsLoading; private string? _showSnapshotUrl; private bool _showSnapshotDialog; @@ -245,12 +305,14 @@ else { _editName = _camera.Name; _editRtspUrl = _camera.RtspUrl; + _recordingEnabled = _camera.RecordingEnabled; } } catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); } finally { _loading = false; } await LoadEventsAsync(); + await LoadRecordingsAsync(); await LoadLatestSnapshotAsync(); } @@ -277,6 +339,27 @@ else finally { _eventsLoading = false; } } + private async Task LoadRecordingsAsync() + { + _recordingsLoading = true; + try + { + var page = await Api.GetCameraRecordingsAsync(Id); + _recordings = page?.Items.ToList() ?? []; + _selectedRecording = _recordings.FirstOrDefault(); + } + catch { _recordings = []; _selectedRecording = null; } + finally { _recordingsLoading = false; } + } + + private void SelectRecording(RecordingItem recording) => _selectedRecording = recording; + private static string RecordingContentUrl(Guid recordingId) => $"/api/recordings/{recordingId:D}/content"; + private static string RecordingDownloadName(Guid recordingId) => $"heimdall-recording-{recordingId:N}.mp4"; + private static string FormatRecordingDuration(double seconds) => TimeSpan.FromSeconds(seconds).ToString("hh\\:mm\\:ss"); + private static string FormatRecordingSize(long bytes) => bytes >= 1024 * 1024 + ? $"{bytes / 1024d / 1024d:0.0} MB" + : $"{bytes / 1024d:0} KB"; + private async Task LoadLatestSnapshotAsync() { _snapshotLoading = true; @@ -360,10 +443,11 @@ else _editSuccess = ""; try { - if (await Api.UpdateCameraAsync(Id, _editName, _editRtspUrl, null)) + if (await Api.UpdateCameraAsync(Id, _editName, _editRtspUrl, null, recordingEnabled: _recordingEnabled)) { _editSuccess = Text["CameraDetail_Updated"]; if (_camera is not null) _camera.Name = _editName; + if (_camera is not null) _camera.RecordingEnabled = _recordingEnabled; } else _editError = Text["CameraDetail_UpdateError"]; } diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index cc3e8c8..6dc3bed 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -163,7 +163,7 @@ public class CamerasController : ControllerBase { if (!this.TryGetUserId(out var actorId)) return Unauthorized(); var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, - request.Manufacturer, request.Model, request.DetectionProfile, actorId); + request.Manufacturer, request.Model, request.DetectionProfile, actorId, request.RecordingEnabled); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) diff --git a/src/Heimdall.Web/Controllers/RecordingsController.cs b/src/Heimdall.Web/Controllers/RecordingsController.cs new file mode 100644 index 0000000..934c11a --- /dev/null +++ b/src/Heimdall.Web/Controllers/RecordingsController.cs @@ -0,0 +1,118 @@ +using System.Security.Claims; +using Heimdall.Api.Security; +using Heimdall.Application.Recordings.Commands.UploadRecording; +using Heimdall.Application.Recordings.Queries.GetCameraRecordings; +using Heimdall.Application.Recordings.Queries.GetRecordingContent; +using Heimdall.Infrastructure.Security; +using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using System.Net.Http.Headers; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api")] +[EnableRateLimiting("Api")] +public sealed class RecordingsController(IMediator mediator, ResourceAccess access) : ControllerBase +{ + private const long MaxSegmentBytes = 100 * 1024 * 1024; + + /// Lists recordings for a camera the authenticated user can access. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("cameras/{cameraId:guid}/recordings")] + public async Task List(Guid cameraId, [FromQuery] DateTime? from, + [FromQuery] DateTime? to, [FromQuery] int page = 1, [FromQuery] int pageSize = 50, + CancellationToken ct = default) + { + var requester = await access.ResolveAsync(User, ct).ConfigureAwait(false); + if (requester is null || requester.Kind != RequesterKind.Human) return NotFound(); + var result = await mediator.Send(new GetCameraRecordingsQuery(cameraId, requester.Id, from, to, page, pageSize), ct) + .ConfigureAwait(false); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Accepts one completed MP4 segment from the currently assigned Agent. + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPut("cameras/{cameraId:guid}/recordings/{recordingId:guid}/content")] + [RequestSizeLimit(MaxSegmentBytes)] + public async Task Upload(Guid cameraId, Guid recordingId, + [FromQuery] DateTime timestamp, [FromQuery] double durationSeconds, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct).ConfigureAwait(false); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await access.CameraAsync(requester, cameraId, ct).ConfigureAwait(false)) return Forbid(); + if (!string.Equals(Request.ContentType?.Split(';')[0].Trim(), "video/mp4", StringComparison.OrdinalIgnoreCase)) + return StatusCode(StatusCodes.Status415UnsupportedMediaType); + if (Request.ContentLength is not long length || length is < 12 or > MaxSegmentBytes) + return StatusCode(StatusCodes.Status413PayloadTooLarge); + + var temporaryPath = Path.Combine(Path.GetTempPath(), $"heimdall-recording-{Guid.NewGuid():N}.mp4"); + try + { + await using (var output = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.ReadWrite, + FileShare.None, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + await Request.Body.CopyToAsync(output, ct).ConfigureAwait(false); + if (output.Length != length) return BadRequest(new { error = "Incomplete recording segment" }); + output.Position = 4; + var signature = new byte[4]; + if (await output.ReadAsync(signature, ct).ConfigureAwait(false) != 4 || + !signature.AsSpan().SequenceEqual("ftyp"u8)) + return BadRequest(new { error = "A valid MP4 segment is required" }); + output.Position = 0; + var result = await mediator.Send(new UploadRecordingCommand(requester.Id, cameraId, recordingId, + timestamp, durationSeconds, length, output), ct).ConfigureAwait(false); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + } + finally + { + try { System.IO.File.Delete(temporaryPath); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + + /// Streams a recording with byte ranges when the configured object provider supports seeking. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("recordings/{recordingId:guid}/content")] + public async Task Download(Guid recordingId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct).ConfigureAwait(false); + if (requester is null || requester.Kind != RequesterKind.Human) return NotFound(); + long? start = null; + long? end = null; + long? suffixLength = null; + if (Request.Headers.TryGetValue("Range", out var headerValue)) + { + if (!RangeHeaderValue.TryParse(headerValue.ToString(), out var range) || + !string.Equals(range.Unit, "bytes", StringComparison.OrdinalIgnoreCase) || range.Ranges.Count != 1) + return StatusCode(StatusCodes.Status416RangeNotSatisfiable); + var item = range.Ranges.Single(); + start = item.From; + end = item.To; + suffixLength = item.From is null ? item.To : null; + if (start is null && suffixLength is null) + return StatusCode(StatusCodes.Status416RangeNotSatisfiable); + } + var result = await mediator.Send(new GetRecordingContentQuery(recordingId, requester.Id, + start, end, suffixLength), ct) + .ConfigureAwait(false); + if (!result.IsSuccess || result.Data is null) + return result.StatusCode == StatusCodes.Status416RangeNotSatisfiable + ? StatusCode(StatusCodes.Status416RangeNotSatisfiable) + : NotFound(); + Response.Headers["Accept-Ranges"] = "bytes"; + Response.ContentLength = result.Data.ContentLength; + if (result.Data.IsPartial) + { + Response.StatusCode = StatusCodes.Status206PartialContent; + Response.Headers.ContentRange = $"bytes {result.Data.Offset}-{result.Data.Offset + result.Data.ContentLength - 1}/{result.Data.SizeBytes}"; + } + return File(result.Data.Stream, result.Data.ContentType, enableRangeProcessing: false); + } +} diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 992e5ec..6558233 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -2367,6 +2367,12 @@ Model + + Record video segments + + + Stores rolling MP4 segments in the configured storage. Disabling stops new segments; retention removes expired recordings. + Name @@ -4075,4 +4081,10 @@ Could not save the role permissions. Role permissions saved. Affected users must sign in again. Saving… + Recordings + Download / export MP4 + No recordings are available for this camera. + Duration + Size + Play diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 3ba52e6..413d4a4 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -2367,6 +2367,12 @@ Modèle + + Enregistrer des segments vidéo + + + Stocke des segments MP4 dans l’emplacement configuré. La désactivation arrête les nouveaux segments ; la rétention supprime les enregistrements arrivés à échéance. + Nom @@ -4075,4 +4081,10 @@ Impossible d’enregistrer les droits du rôle. Droits du rôle enregistrés. Les utilisateurs concernés devront se reconnecter. Enregistrement… + Enregistrements + Télécharger / exporter en MP4 + Aucun enregistrement n’est disponible pour cette caméra. + Durée + Taille + Lire diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index 96b09b7..b98051f 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -2367,6 +2367,12 @@ Modèle + + Enregistrer des segments vidéo + + + Stocke des segments MP4 dans l’emplacement configuré. La désactivation arrête les nouveaux segments ; la rétention supprime les enregistrements arrivés à échéance. + Nom @@ -4075,4 +4081,10 @@ Could not save the role permissions. Role permissions saved. Affected users must sign in again. Saving… + Recordings + Download / export MP4 + No recordings are available for this camera. + Duration + Size + Play diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 75c0e2f..ed5e844 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -508,6 +508,13 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync($"api/cameras/{id}", Json); } + public async Task?> GetCameraRecordingsAsync(Guid id, int page = 1, int pageSize = 20) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/cameras/{id}/recordings?page={page}&pageSize={pageSize}", Json); + } + public async Task> RequestCameraSnapshotAsync(Guid id) { var client = CreateClient(); @@ -528,11 +535,11 @@ public class HeimdallApiClient : IDisposable } public async Task UpdateCameraAsync(Guid id, string name, string? rtspUrl, string? status, - string? manufacturer = null, string? model = null) + string? manufacturer = null, string? model = null, bool? recordingEnabled = null) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/cameras/{id}", - new { name, rtspUrl, status, manufacturer, model }, Json); + new { name, rtspUrl, status, manufacturer, model, recordingEnabled }, Json); return response.IsSuccessStatusCode; } @@ -1045,6 +1052,7 @@ public class CameraItem public string? RtspUrl { get; set; } public string Status { get; set; } = "Unknown"; public DateTime CreatedAt { get; set; } + public bool RecordingEnabled { get; set; } } /// @@ -1347,6 +1355,14 @@ public record EventItem( [property: JsonPropertyName("occurredAt")] DateTime OccurredAt, [property: JsonPropertyName("createdAt")] DateTime CreatedAt); +public record RecordingItem( + [property: JsonPropertyName("id")] Guid Id, + [property: JsonPropertyName("cameraId")] Guid CameraId, + [property: JsonPropertyName("timestamp")] DateTime Timestamp, + [property: JsonPropertyName("durationSeconds")] double DurationSeconds, + [property: JsonPropertyName("sizeBytes")] long SizeBytes, + [property: JsonPropertyName("contentUrl")] string ContentUrl); + public record EventPageResult( [property: JsonPropertyName("items")] List Items, [property: JsonPropertyName("totalCount")] int TotalCount, diff --git a/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs new file mode 100644 index 0000000..3d54255 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs @@ -0,0 +1,22 @@ +namespace Heimdall.Agent.Tests; + +public sealed class AgentRecordingServiceTests +{ + [Fact] + public void CreateStartInfo_UsesSegmentedMp4AndTreatsRtspAsOneArgument() + { + const string rtsp = "rtsp://user:p@ss@camera/stream?profile=1&x=2"; + var info = AgentRecordingService.CreateStartInfo("ffmpeg-test", rtsp, "/tmp/segments", 45); + + info.FileName.ShouldBe("ffmpeg-test"); + info.ArgumentList.ShouldContain(rtsp); + info.ArgumentList.ShouldContain("-segment_time"); + info.ArgumentList.ShouldContain("45"); + info.ArgumentList.ShouldContain("-segment_format"); + info.ArgumentList.ShouldContain("mp4"); + info.ArgumentList.ShouldContain("-segment_list_type"); + info.ArgumentList.ShouldContain("csv"); + info.ArgumentList.ShouldContain("/tmp/segments/segment-%06d.mp4"); + info.UseShellExecute.ShouldBeFalse(); + } +} diff --git a/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs index 8657142..5f26edd 100644 --- a/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs +++ b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs @@ -52,6 +52,19 @@ public class CameraConfigStoreTests store.Cameras.ShouldHaveSingleItem().Enabled.ShouldBeFalse(); } + [Fact] + public void ApplyCameraSetting_RecordingIsOptInAndPropagates() + { + var store = new CameraConfigStore(); + var id = Guid.NewGuid(); + store.ApplyCameraSetting($"camera.{id}.name", "Door"); + store.Cameras.ShouldHaveSingleItem().RecordingEnabled.ShouldBeFalse(); + + store.ApplyCameraSetting($"camera.{id}.recording_enabled", "true"); + + store.Cameras.ShouldHaveSingleItem().RecordingEnabled.ShouldBeTrue(); + } + [Fact] public void ApplyCameraSetting_InvalidKey_Ignored() { diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs index 691f0db..8cff26b 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs @@ -59,6 +59,24 @@ public class GetEffectiveAgentConfigHandlerTests result.Data!["autoupdateenabled"].ShouldBe("true"); } + [Fact] + public async Task Get_effective_config_should_ship_recording_opt_in_for_assigned_camera() + { + var site = new Site("recording-site"); + var agent = new Agent(site.Id, "recording-agent", "host", "1.0.0"); + var camera = new Camera(site.Id, "front door", "rtsp://camera/stream"); + camera.AssignAgent(agent.Id); + camera.SetStatus(CameraStatus.Online); + camera.SetRecordingEnabled(true); + var context = CreateContext(agents: [agent], sites: [site], cameras: [camera]); + var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector); + + var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data![ $"camera.{camera.Id}.recording_enabled"].ShouldBe("true"); + } + [Fact] public async Task Get_effective_config_should_merge_app_and_agent_settings() { diff --git a/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs index f31ba6c..a53f2a8 100644 --- a/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs @@ -35,6 +35,31 @@ public class LocalStorageProviderTests : IDisposable (await reader.ReadToEndAsync()).ShouldBe("hello storage"); } + [Fact] + public async Task DownloadRange_ReturnsOnlyRequestedBytesAndKeepsContentLengthStable() + { + await _provider.UploadAsync("recordings/camera/segment.mp4", + new MemoryStream(Encoding.ASCII.GetBytes("0123456789")), "video/mp4"); + + await using var stream = await _provider.DownloadRangeAsync("recordings/camera/segment.mp4", 2, 5); + stream.ShouldNotBeNull(); + stream.CanSeek.ShouldBeFalse(); + stream.Length.ShouldBe(4); + using var reader = new StreamReader(stream); + (await reader.ReadToEndAsync()).ShouldBe("2345"); + stream.Length.ShouldBe(4); + } + + [Fact] + public async Task DownloadRange_EndBeyondObjectLength_IsRejected() + { + await _provider.UploadAsync("recordings/camera/segment.mp4", + new MemoryStream(Encoding.ASCII.GetBytes("0123456789")), "video/mp4"); + + await Should.ThrowAsync(() => + _provider.DownloadRangeAsync("recordings/camera/segment.mp4", 2, 10)); + } + [Fact] public async Task Download_Missing_ReturnsNull() { diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs index ab3cc9d..69abeb4 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -92,6 +92,28 @@ public class CameraDetailTests : PageTestBase }); } + [Fact] + public void CameraDetail_AfficheLecteurEtExportPourLesEnregistrementsAutorises() + { + var recordingId = Guid.NewGuid(); + Handler.OnGet($"api/cameras/{CameraId}/recordings", new PagedData( + [new RecordingItem(recordingId, CameraId, DateTime.UtcNow.AddMinutes(-2), 12.5, 4096, + $"/api/recordings/{recordingId:D}/content")], 1, 1, 20)); + HandlerCamera(Camera()); + Handler.OnGet("api/events/camera/", new List()); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("([recording], 1, 1, 20)); + + var result = await _sut.GetCameraRecordingsAsync(cameraId); + + Assert.NotNull(result); + Assert.Single(result.Items); + Assert.Equal(recording.Id, result.Items[0].Id); + Assert.Contains($"api/cameras/{cameraId}/recordings?page=1&pageSize=20", _handler.LastRequest!.RequestUri!.ToString()); + } + [Fact] public async Task UpdateCameraAsync_WhenSuccess_ReturnsTrue() { @@ -293,6 +310,20 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable Assert.True(result); } + [Fact] + public async Task UpdateCameraAsync_SendsRecordingEnabledOptIn() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.OK); + + var result = await _sut.UpdateCameraAsync(Guid.NewGuid(), "Cam", "rtsp://cam", null, + recordingEnabled: true); + + Assert.True(result); + using var body = System.Text.Json.JsonDocument.Parse(await _handler.LastRequest!.Content!.ReadAsStringAsync()); + Assert.True(body.RootElement.GetProperty("recordingEnabled").GetBoolean()); + } + [Fact] public async Task DeleteCameraAsync_WhenSuccess_ReturnsTrue() { diff --git a/todo.md b/todo.md index 9599e49..6ac8fa1 100644 --- a/todo.md +++ b/todo.md @@ -28,7 +28,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. - [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. -- [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), et la validation du changement de provider sur stockage déployé. +- [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé. - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. - [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. @@ -46,9 +46,10 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. -- [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt; le test réel `RealOnnx_CpuModel_ProcessesFullHdImage` a ensuite réussi seul avec ce package. Reste à fournir/publier une image/runtime CUDA compatible, l'exposer via installation/UI, valider la recette Compose jetable et exécuter sur matériel GPU réel; aucun GPU n'est déclaré validé. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt. Test d'inférence ONNX CPU 1080p autonome : 1/1. Restent image/runtime GPU, sélection UI/installateur, manifeste de release, test complet et matériel CUDA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** L'édition des groupes permet maintenant de lister les caméras des sites, d'accorder/révoquer les accès de groupe et d'afficher les noms de site/caméra via l'API existante. Restent la validation produit et la vérification de l'union accès direct/groupe ainsi que des priorités dans l'interface. -- 2.54.1 From dee59ed0dbfa4354e6311bee1efb45f5c5f3d900 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 22:31:04 +0100 Subject: [PATCH 11/40] docs: remove duplicate FEAT-01 todo entry --- todo.md | 1 - 1 file changed, 1 deletion(-) diff --git a/todo.md b/todo.md index 6ac8fa1..91891c9 100644 --- a/todo.md +++ b/todo.md @@ -46,7 +46,6 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. -- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt. Test d'inférence ONNX CPU 1080p autonome : 1/1. Restent image/runtime GPU, sélection UI/installateur, manifeste de release, test complet et matériel CUDA réel. -- 2.54.1 From 495740292a4afed5ee043b59e54d5f138a30cfa6 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 22:45:14 +0100 Subject: [PATCH 12/40] feat(web): add camera-scoped WebRTC live view --- docker/docker-compose.prod.yml | 8 +- docker/docker-compose.webrtc-local-test.yml | 58 +++++++ docker/docker-compose.webrtc-test.yml | 22 +++ docker/docker-compose.webrtc.yml | 25 +++ docker/docker-compose.yml | 8 + docker/mediamtx.local-test.yml | 17 ++ docker/mediamtx.synthetic-source.yml | 15 ++ docker/mediamtx.yml | 23 +++ docs/docker-compose.md | 77 ++++++++- skills/webrtc-live/SKILL.md | 72 ++++++++ src/Heimdall.Agent/Program.cs | 1 + .../Services/LiveCameraRelayService.cs | 116 +++++++++++++ .../Components/Pages/CameraDetail.razor | 47 ++++- .../Controllers/LiveMediaController.cs | 162 ++++++++++++++++++ .../Localization/SharedResources.en.resx | 6 +- .../Localization/SharedResources.fr.resx | 6 +- .../Localization/SharedResources.resx | 6 +- src/Heimdall.Web/Program.cs | 2 + .../Security/LiveMediaSessionLimiter.cs | 72 ++++++++ src/Heimdall.Web/Security/LiveMediaTickets.cs | 55 ++++++ src/Heimdall.Web/wwwroot/js/live-view.js | 44 +++++ .../LiveCameraRelayServiceTests.cs | 32 ++++ .../LiveMediaSessionLimiterTests.cs | 33 ++++ .../LiveMediaTicketsTests.cs | 52 ++++++ todo.md | 4 +- 25 files changed, 954 insertions(+), 9 deletions(-) create mode 100644 docker/docker-compose.webrtc-local-test.yml create mode 100644 docker/docker-compose.webrtc-test.yml create mode 100644 docker/docker-compose.webrtc.yml create mode 100644 docker/mediamtx.local-test.yml create mode 100644 docker/mediamtx.synthetic-source.yml create mode 100644 docker/mediamtx.yml create mode 100644 skills/webrtc-live/SKILL.md create mode 100644 src/Heimdall.Agent/Services/LiveCameraRelayService.cs create mode 100644 src/Heimdall.Web/Controllers/LiveMediaController.cs create mode 100644 src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs create mode 100644 src/Heimdall.Web/Security/LiveMediaTickets.cs create mode 100644 src/Heimdall.Web/wwwroot/js/live-view.js create mode 100644 tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs create mode 100644 tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs create mode 100644 tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index c86591f..932c387 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -47,6 +47,12 @@ services: ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} ASPNETCORE_URLS: http://+:8080 Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*} + LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-} + LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-} + LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false} + LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} + LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} + LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} Sentry__Dsn: ${SENTRY_DSN:-} Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05} Sentry__Release: ${SENTRY_RELEASE:-} @@ -91,5 +97,5 @@ secrets: networks: heimdall-net: - name: heimdall-net + name: ${HEIMDALL_NETWORK_NAME:-heimdall-net} driver: bridge diff --git a/docker/docker-compose.webrtc-local-test.yml b/docker/docker-compose.webrtc-local-test.yml new file mode 100644 index 0000000..5ae6683 --- /dev/null +++ b/docker/docker-compose.webrtc-local-test.yml @@ -0,0 +1,58 @@ +# Loopback-only media services for disposable acceptance, never production. +services: + mediamtx: + image: bluenviron/mediamtx:1.21.3 + restart: unless-stopped + environment: + HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin} + MTX_AUTHMETHOD: http + MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central callback URL} + ports: + - "127.0.0.1:${HEIMDALL_TEST_PUBLISH_PORT:-18555}:8554/tcp" + - "127.0.0.1:${HEIMDALL_TEST_WHEP_PORT:-18889}:8889/tcp" + - "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:8189/udp" + volumes: + - ./mediamtx.local-test.yml:/mediamtx.yml:ro + networks: + - heimdall-net + + heimdall-agent: + image: heimdall-agent:webrtc-test + build: + context: .. + dockerfile: docker/Dockerfile.agent + restart: unless-stopped + network_mode: host + user: "1654:1654" + environment: + ASPNETCORE_URLS: http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081} + Agent__CentralUrl: http://127.0.0.1:${WEB_PORT:-5000} + Agent__AllowInsecureHttp: "true" + Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:-} + Agent__AgentName: webrtc-synthetic-agent + Agent__StateDirectory: /var/lib/heimdall + volumes: + - heimdall_agent_state:/var/lib/heimdall + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081}/healthz"] + interval: 10s + timeout: 3s + retries: 3 + start_period: 20s + depends_on: + agent-state-init: + condition: service_completed_successfully + + agent-state-init: + image: heimdall-agent:webrtc-test + build: + context: .. + dockerfile: docker/Dockerfile.agent + user: "0:0" + entrypoint: ["chown", "-R", "1654:1654", "/state"] + volumes: + - heimdall_agent_state:/state + restart: "no" + +volumes: + heimdall_agent_state: diff --git a/docker/docker-compose.webrtc-test.yml b/docker/docker-compose.webrtc-test.yml new file mode 100644 index 0000000..1c02a98 --- /dev/null +++ b/docker/docker-compose.webrtc-test.yml @@ -0,0 +1,22 @@ +# Test-only synthetic camera source. Exposes one local RTSP port so an Agent +# can be configured through Central to pull this generated H.264 stream. +services: + synthetic-camera: + image: bluenviron/mediamtx:1.21.3 + restart: unless-stopped + ports: + - "127.0.0.1:${HEIMDALL_SYNTHETIC_RTSP_PORT:-18554}:8554/tcp" + volumes: + - ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro + networks: + - heimdall-net + + synthetic-camera-publisher: + image: jrottenberg/ffmpeg:7.1-alpine + restart: unless-stopped + entrypoint: ["/bin/sh", "-c"] + command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -profile:v baseline -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 2; done"] + depends_on: + - synthetic-camera + networks: + - heimdall-net diff --git a/docker/docker-compose.webrtc.yml b/docker/docker-compose.webrtc.yml new file mode 100644 index 0000000..4fd8ede --- /dev/null +++ b/docker/docker-compose.webrtc.yml @@ -0,0 +1,25 @@ +# Optional MediaMTX for live camera video. Start after the core stack has +# created heimdall-net. Public DNS and certificates are deployment supplied. +services: + mediamtx: + image: bluenviron/mediamtx:1.21.3 + restart: unless-stopped + environment: + HEIMDALL_WEBRTC_PUBLIC_HOST: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname} + HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin} + MTX_AUTHMETHOD: http + MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central MediaMTX callback URL} + ports: + - "${HEIMDALL_RTSPS_PORT:-8322}:8322/tcp" + - "${HEIMDALL_WHEP_PORT:-8889}:8889/tcp" + - "${HEIMDALL_WEBRTC_UDP_PORT:-8189}:8189/udp" + volumes: + - ./mediamtx.yml:/mediamtx.yml:ro + - ${HEIMDALL_LIVE_MEDIA_CERT_DIR:?Set directory containing server.crt and server.key}:/certs:ro + networks: + - heimdall-net + +networks: + heimdall-net: + external: true + name: ${HEIMDALL_NETWORK_NAME:-heimdall-net} diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 2435dda..b5a4177 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -36,6 +36,13 @@ services: ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development} ASPNETCORE_URLS: http://+:8080 Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*} + LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-} + LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-} + LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false} + LiveMedia__AllowInsecureHttp: ${HEIMDALL_ALLOW_INSECURE_HTTP:-false} + LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} + LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} + LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} ports: - "${WEB_PORT:-5000}:8080" volumes: @@ -61,4 +68,5 @@ volumes: networks: heimdall-net: + name: ${HEIMDALL_NETWORK_NAME:-heimdall-net} driver: bridge diff --git a/docker/mediamtx.local-test.yml b/docker/mediamtx.local-test.yml new file mode 100644 index 0000000..2ac6cd9 --- /dev/null +++ b/docker/mediamtx.local-test.yml @@ -0,0 +1,17 @@ +# Loopback-only insecure listeners for disposable workstation acceptance only. +logLevel: warn +rtsp: true +rtspTransports: [tcp] +rtspEncryption: "no" +rtspAddress: :8554 +webrtc: true +webrtcAddress: :8889 +webrtcEncryption: false +webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}'] +webrtcLocalUDPAddress: :8189 +webrtcAdditionalHosts: ['127.0.0.1'] +pathDefaults: + source: publisher + record: false +paths: + all_others: diff --git a/docker/mediamtx.synthetic-source.yml b/docker/mediamtx.synthetic-source.yml new file mode 100644 index 0000000..55a72b0 --- /dev/null +++ b/docker/mediamtx.synthetic-source.yml @@ -0,0 +1,15 @@ +logLevel: warn +rtsp: true +rtspTransports: [tcp] +rtspEncryption: "no" +rtspAddress: :8554 +authMethod: internal +authInternalUsers: + - user: any + pass: + ips: [] + permissions: + - action: publish + - action: read +paths: + all_others: diff --git a/docker/mediamtx.yml b/docker/mediamtx.yml new file mode 100644 index 0000000..a60015a --- /dev/null +++ b/docker/mediamtx.yml @@ -0,0 +1,23 @@ +logLevel: warn +rtsp: true +rtspTransports: [tcp] +rtspEncryption: strict +rtspsAddress: :8322 +rtspServerCert: /certs/server.crt +rtspServerKey: /certs/server.key + +webrtc: true +webrtcAddress: :8889 +webrtcEncryption: true +webrtcServerCert: /certs/server.crt +webrtcServerKey: /certs/server.key +webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}'] +webrtcLocalUDPAddress: :8189 +webrtcAdditionalHosts: ['${HEIMDALL_WEBRTC_PUBLIC_HOST}'] + +pathDefaults: + source: publisher + record: false + +paths: + all_others: diff --git a/docs/docker-compose.md b/docs/docker-compose.md index a261a83..2e1c4ae 100644 --- a/docs/docker-compose.md +++ b/docs/docker-compose.md @@ -138,7 +138,7 @@ docker compose --env-file docker/.env -f docker/docker-compose.backup.yml up -d Configure Ollama at `http://ollama:11434` in Central's AI settings when enabled. Choose RustFS as the storage provider in Central and use `http://rustfs:9000` as its endpoint. Configure the ntfy server URL in Central's notification settings. -TURN is not required until WebRTC is enabled. +Live view can connect directly when ICE succeeds. For clients behind restrictive NAT/firewalls, deploy and validate TURN, then configure its URLs and matching shared secret in Central; without a reachable relay, those clients may not connect. Redis is provided as a standalone service but is not currently required by Central. Backups are independent of the core startup and require the core network and PostgreSQL service to be running. @@ -146,3 +146,78 @@ network and PostgreSQL service to be running. See [GPU Agent notes](gpu-runtime.md) and [Agent update signing](agent-release-signing.md) for device access and trusted-key setup. + +## Optional live video with WebRTC + +The live-view vertical uses the separately maintained MediaMTX image. It is not +started with the core stack. Configure Central with the public `HEIMDALL_WHEP_URL` +and `HEIMDALL_PUBLISH_RTSPS_URL` (including scheme, host and port only). Provide +`HEIMDALL_MEDIAMTX_AUTH_URL` to the MediaMTX container; when both services share +the default Docker network this can use the Central service name and internal +port. Configure `HEIMDALL_WEBRTC_PUBLIC_HOST`, +`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and `HEIMDALL_LIVE_MEDIA_CERT_DIR` for the +public listener and its TLS certificate (`server.crt` and `server.key`). The +certificate must cover both public WHEP and RTSPS hostnames. Open the configured +RTSPS/WHEP TCP ports and WebRTC ICE UDP port in the firewall. Add STUN URLs under +`LiveMedia:IceServers`; for TURN REST credentials set +`LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns +five-minute HMAC credentials to the browser; the shared secret is never sent. +When using `docker-compose.coturn.yml`, configure the Central secret from the same +protected secret source as `docker/secrets/coturn_secret`; protect the Central +`.env` with owner-only permissions. + +Start the core project first so its external `heimdall-net` network exists, then +start MediaMTX with a separate project name: + +```sh +docker compose --env-file docker/.env -f docker/docker-compose.webrtc.yml -p heimdall-live up -d +``` + +Stop only this optional project with `docker compose ... -p heimdall-live down`. +Live publishing requires an assigned Agent and an online, enabled camera. Agent +relays are video-only H.264 passthrough, limited to two simultaneous cameras per +Agent. Central reserves eight viewers per camera and two per user in its process; +use one Central instance until shared reservation storage is configured. A stream +with a browser-incompatible codec is not transcoded. The WHEP read session +expires after ten minutes; the browser deletes the WHEP resource on +stop/navigation. Physical camera and external TURN validation remain deployment +acceptance work. + +### Disposable live-view acceptance + +For an isolated local playback test, use the local-only override and synthetic +source Compose files. Generate a unique `.env` outside the repository with new +PostgreSQL/JWT secrets, loopback ports, `HEIMDALL_NETWORK_NAME`, +`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and +`HEIMDALL_MEDIAMTX_AUTH_URL=http://heimdall:8080/api/live-media/auth`. +Configure `HEIMDALL_WHEP_URL=http://127.0.0.1:`, +`HEIMDALL_PUBLISH_RTSPS_URL=rtsp://127.0.0.1:`, +`HEIMDALL_ALLOW_INSECURE_HTTP=true`, +`HEIMDALL_ALLOW_INSECURE_RTSP=true`, and +`HEIMDALL_WEBRTC_ALLOWED_ORIGIN=http://localhost:`. Set +`HEIMDALL_NETWORK_NAME` to a unique network name and select unused values for +`WEB_PORT`, `HEIMDALL_TEST_PUBLISH_PORT`, `HEIMDALL_TEST_WHEP_PORT`, +`HEIMDALL_TEST_ICE_PORT`, `HEIMDALL_SYNTHETIC_RTSP_PORT`, and +`HEIMDALL_TEST_AGENT_PORT`. Insecure protocols are allowed only because all media +ports bind to loopback in this recipe. Then start Central, the local MediaMTX, +and synthetic source from changed source, excluding the Agent until a site token +is available: + +```sh +docker compose -p "$project" --env-file "$env_file" \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.webrtc-local-test.yml \ + -f docker/docker-compose.webrtc-test.yml \ + up -d --build postgresql heimdall mediamtx synthetic-camera synthetic-camera-publisher +``` + +Complete first-admin setup, create a site, put its generated test site token in +the disposable `.env`, and start `heimdall-agent` from the same Compose files. +Create and assign an online camera with the synthetic source RTSP URL, then open +its detail page and start live video. Verify an ungranted user is denied, stop +and disable the camera, and check the Agent process and WHEP session are closed. +Use unique ports and the unique network value for each run. Tear down only this +project with `down --volumes --remove-orphans`, confirm its containers, named +volumes and network are gone, and delete its temporary environment/secret files. +This recipe is HTTP/RTSP loopback-only; production configuration remains RTSPS +and HTTPS with a trusted certificate. diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md new file mode 100644 index 0000000..df5110e --- /dev/null +++ b/skills/webrtc-live/SKILL.md @@ -0,0 +1,72 @@ +# Live WebRTC implementation and acceptance + +The current vertical provides Agent RTSP re-publishing, Central camera-scoped +Data Protection tickets and MediaMTX auth, and a camera detail WHEP player. +`FEAT-01` stays open until the disposable synthetic acceptance below passes +and external network behavior is measured. + +## Required architecture + +- Keep camera assignment and stream lifecycle in Agent. Only an enabled camera + present in the current Central assignment snapshot may be published. Stop the + publisher when assignment, enablement, configuration, or Agent lifetime ends. +- Use MediaMTX as the WebRTC/WHEP media server. Agent publishes the camera's + browser-compatible H.264 stream to a camera-ID path. Prefer passthrough when + the source codec is compatible; otherwise make transcoding an explicit, + bounded option. Start video-only; audio and PTZ require separate acceptance. +- Central issues random, short-lived, purpose-separated publish and read claims + scoped to one camera and one action. Protect claims with the shared Heimdall + Data Protection key ring. MediaMTX HTTP auth must validate exact path, action, + protocol, expiry, Agent assignment for publish, and current user camera rights + for read. Never put RTSP credentials, Central API keys, or reusable TURN + credentials in browser-visible URLs or logs. +- Browser obtains a read session from the authenticated camera API and performs + WHEP with that short-lived bearer token. ICE servers and public WHEP URL must + come from deployment configuration, never source-code hostnames. Do not issue + static TURN credentials to the browser. +- Bound simultaneous Agent publishers and viewers, request duration, retries, + FFmpeg process count, and session lifetime. Ensure cancellation/config changes + reap child processes and release permits. + +## Implementation references + +Use MediaMTX's maintained documentation as the protocol reference: + +- [WHEP/WebRTC read](https://mediamtx.org/docs/read/webrtc) +- [HTTP authentication callbacks](https://mediamtx.org/docs/features/authentication) +- [ICE, TURN, codec and latency details](https://mediamtx.org/docs/features/webrtc-specific-features) +- [Configuration reference](https://mediamtx.org/docs/references/configuration-file) +- [RTSP camera/source behavior](https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/08-rtsp-cameras-and-servers.md) +- [MediaMTX license](https://github.com/bluenviron/mediamtx/blob/main/LICENSE) + +Use H.264 without B-frames for browser compatibility and latency. Validate +actual negotiation in browsers; a successful RTSP publish does not prove WHEP. + +## Required acceptance + +Run from changed source in an isolated disposable Compose project with unique +project name, generated credentials, ports and volumes. The optional +`docker/docker-compose.webrtc-test.yml` starts a local-only generated H.264 +camera feed. Use `docker/docker-compose.webrtc-local-test.yml` plus +`docker/docker-compose.webrtc-test.yml` with the core `docker-compose.yml` in one +unique project. Set unique generated database/JWT credentials, loopback ports, +`HEIMDALL_NETWORK_NAME`, `HEIMDALL_MEDIAMTX_AUTH_URL`, WHEP/publish URLs, and the +Central browser origin in an env file outside the repository. Start Central, +MediaMTX and the synthetic feed first; bootstrap the first admin and site, then +place the generated synthetic site token in the disposable env file and start +the Agent. Configure its assigned camera against the host loopback RTSP port. Do not depend on a physical camera. Verify all of the following: + +1. An assigned Agent receives only its assigned camera's short-lived publish + credential and publishes synthetic H.264 to that camera path. +2. An authorized user obtains a short-lived read claim and a browser-compatible + WHEP session; the browser receives decoded frames. +3. An unassigned Agent, cross-camera claim, wrong action/path/protocol, expired + token, and user without camera access are rejected. +4. Disable/reassign camera, stop Agent, end viewer, and expire claim; verify the + matching processes/sessions terminate and resource counts return to baseline. +5. Logs and API errors contain no credentials, raw tokens, RTSP URLs, or ICE + secrets. Verify configured ICE/TURN candidate behavior separately. +6. Tear down only that Compose project with volumes/orphans, then verify its + containers, volumes and network are gone. + +Record LAN browser and external TURN runs independently. Current focused API/Web and Agent tests pass. Disposable Compose verified Central bootstrap/site creation, Agent registration, synthetic camera assignment, publish-session issuance and relay start, read ticket callback acceptance, forged-ticket denial, unknown-camera denial, and teardown with no remaining project containers, volumes or networks. A deliberately invalid SDP reached MediaMTX and returned 400; a browser-decoded frame and API-driven disable stop were not verified. Physical camera, LAN, external TURN and real SDP/frame playback remain unvalidated; keep FEAT-01 open until these acceptance gaps are closed. diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 1ceb708..b6c2d18 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -172,6 +172,7 @@ builder.Services.AddSingleton(sp => new SnapshotPipelineService(new SnapshotPipe sp.GetRequiredService()))); builder.Services.AddHostedService(sp => sp.GetRequiredService()); builder.Services.AddHostedService(); +builder.Services.AddHostedService(); // Log capture & upload to Central (ticket #50) builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/LiveCameraRelayService.cs b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs new file mode 100644 index 0000000..f0b31ec --- /dev/null +++ b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs @@ -0,0 +1,116 @@ +using System.Diagnostics; +using System.Net.Http.Json; +using System.Text.Json.Serialization; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Services; + +/// Re-publishes assigned primary streams to the configured Central MediaMTX. +public sealed class LiveCameraRelayService( + AgentState state, + IOptions options, + CameraConfigStore cameras, + IHttpClientFactory clients, + ILogger logger) : BackgroundService +{ + private const int MaxPublishers = 2; + private readonly Dictionary _relays = []; + private readonly Dictionary _retryAt = []; + private sealed record Relay(Process Process, DateTimeOffset RenewAt); + private sealed record PublishSession(string Url, DateTimeOffset RenewAt); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + while (!stoppingToken.IsCancellationRequested) + { + try { await SynchronizeAsync(stoppingToken); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + catch (Exception ex) { logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); } + try { await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + } + } + finally { await StopAllAsync(); } + } + + private async Task SynchronizeAsync(CancellationToken ct) + { + var assigned = SelectAssignedCameras(cameras); + foreach (var id in _relays.Keys.Where(id => !assigned.ContainsKey(id)).ToArray()) + await StopAsync(id); + + foreach (var camera in assigned.Values) + { + if (_relays.TryGetValue(camera.CameraId, out var relay) && !relay.Process.HasExited && + relay.RenewAt > DateTimeOffset.UtcNow) continue; + await StopAsync(camera.CameraId); + if (state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(state.ApiKey) || + _retryAt.GetValueOrDefault(camera.CameraId) > DateTimeOffset.UtcNow) continue; + if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = DateTimeOffset.UtcNow.AddSeconds(20); + } + } + + internal static IReadOnlyDictionary SelectAssignedCameras(CameraConfigStore cameras) => + cameras.HasCentralConfiguration + ? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.RtspUrl)) + .Take(MaxPublishers).ToDictionary(c => c.CameraId) + : new Dictionary(); + + private static bool IsRtspSource(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && + (uri.Scheme.Equals("rtsp", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("rtsps", StringComparison.OrdinalIgnoreCase)); + + private async Task StartAsync(AgentCameraConfig camera, CancellationToken ct) + { + var client = clients.CreateClient(); + client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", state.ApiKey); + using var response = await client.PostAsync( + $"{options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session", + content: null, ct); + if (!response.IsSuccessStatusCode) return false; + var session = await response.Content.ReadFromJsonAsync(cancellationToken: ct); + if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false; + + var source = camera.RtspUrl; + var start = new ProcessStartInfo { FileName = "ffmpeg", UseShellExecute = false, + RedirectStandardError = true, RedirectStandardOutput = false, CreateNoWindow = true }; + foreach (var arg in new[] { "-nostdin", "-hide_banner", "-loglevel", "error", "-fflags", "nobuffer", "-flags", "low_delay", "-rtsp_transport", "tcp", "-i", source, + "-map", "0:v:0", "-an", "-c:v", "copy", "-f", "rtsp", "-rtsp_transport", "tcp", destination.ToString() }) + start.ArgumentList.Add(arg); + try + { + var process = Process.Start(start); + if (process is null) return false; + _ = DrainErrorsAsync(process); + _relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30)); + logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId); + return true; + } + catch (Exception ex) { logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; } + } + + private static async Task DrainErrorsAsync(Process process) + { + try { while (await process.StandardError.ReadLineAsync() is not null) { } } + catch (IOException) { } + } + + private async Task StopAsync(Guid cameraId) + { + if (!_relays.Remove(cameraId, out var relay)) return; + try + { + if (!relay.Process.HasExited) relay.Process.Kill(entireProcessTree: true); + await relay.Process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3)); + } + catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or TimeoutException) + { logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); } + finally { relay.Process.Dispose(); } + } + + private async Task StopAllAsync() + { + foreach (var cameraId in _relays.Keys.ToArray()) await StopAsync(cameraId); + } +} diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 17d320e..1c63c88 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -6,7 +6,8 @@ @inject NavigationManager Nav @inject UiText Text @inject UiLanguageService Language -@implements IDisposable +@inject IJSRuntime JS +@implements IAsyncDisposable @@ -77,6 +78,16 @@ else + +
+ @Text["CameraDetail_Live"] + + @(_liveEnabled ? Text["CameraDetail_StopLive"] : Text["CameraDetail_WatchLive"]) + +
+ +
+ @* ─── Informations & actions ─── *@ @Text["CameraDetail_Information"] @@ -533,11 +544,43 @@ else _ => Color.Default }; - public void Dispose() + private ElementReference _liveVideo; + private IJSObjectReference? _liveModule; + private bool _liveEnabled; + private bool _liveStarting; + + private async Task ToggleLive() + { + if (_camera is null || _liveStarting) return; + _liveStarting = true; + try + { + _liveModule ??= await JS.InvokeAsync("import", "./js/live-view.js"); + if (_liveEnabled) + { + await _liveModule.InvokeVoidAsync("stop", _camera.Id); + _liveEnabled = false; + } + else + { + await _liveModule.InvokeVoidAsync("start", _camera.Id, _liveVideo); + _liveEnabled = true; + } + } + catch { Snackbar.Add(Text["CameraDetail_LiveUnavailable"], Severity.Warning); } + finally { _liveStarting = false; } + } + + public async ValueTask DisposeAsync() { Language.LanguageChanged -= OnLanguageChanged; _disposed = true; _refreshCts?.Cancel(); _refreshCts?.Dispose(); + if (_liveModule is not null) + { + try { if (_camera is not null) await _liveModule.InvokeVoidAsync("stop", _camera.Id); await _liveModule.DisposeAsync(); } + catch (JSDisconnectedException) { } + } } } diff --git a/src/Heimdall.Web/Controllers/LiveMediaController.cs b/src/Heimdall.Web/Controllers/LiveMediaController.cs new file mode 100644 index 0000000..dc8508d --- /dev/null +++ b/src/Heimdall.Web/Controllers/LiveMediaController.cs @@ -0,0 +1,162 @@ +using System.Text.Json.Serialization; +using System.Security.Cryptography; +using System.Globalization; +using System.Security.Claims; +using System.Text; +using Heimdall.Application.Auth.Services; +using Heimdall.Api.Security; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/live-media")] +[EnableRateLimiting("Api")] +public sealed class LiveMediaController( + IApplicationDbContext db, + ResourceAccess access, + ICameraAccessService cameraAccess, + IIdentityAccountService identity, + LiveMediaSessionLimiter sessions, + LiveMediaTickets tickets, + IConfiguration configuration) : ControllerBase +{ + private static readonly TimeSpan TicketLifetime = TimeSpan.FromMinutes(2); + + public sealed record AuthRequest([property: JsonPropertyName("token")] string? Token, + [property: JsonPropertyName("user")] string? User, + [property: JsonPropertyName("password")] string? Password, + [property: JsonPropertyName("action")] string? Action, + [property: JsonPropertyName("path")] string? Path, + [property: JsonPropertyName("protocol")] string? Protocol); + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpPost("cameras/{cameraId:guid}/session")] + public async Task CreateReadSession(Guid cameraId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + var camera = await db.Cameras.AsNoTracking().Where(c => c.Id == cameraId) + .Select(c => new { c.Status, c.AgentId }).SingleOrDefaultAsync(ct); + if (camera is null) return NotFound(); + if (camera.Status != CameraStatus.Online || camera.AgentId is null) + return Conflict(new { error = "Camera is not available for live view" }); + + var whep = configuration["LiveMedia:WhepUrl"]; + if (!Uri.TryCreate(whep, UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("https" or "http") || + !string.IsNullOrEmpty(endpoint.UserInfo) || !string.IsNullOrEmpty(endpoint.Query) || !string.IsNullOrEmpty(endpoint.Fragment) || + (endpoint.Scheme != "https" && !configuration.GetValue("LiveMedia:AllowInsecureHttp"))) + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "Live media is not configured" }); + var securityStamp = User.FindFirstValue(AccountSessionPolicy.StampClaim); + if (string.IsNullOrWhiteSpace(securityStamp)) return Forbid(); + if (!sessions.TryAcquire(cameraId, requester.Id, out var sessionId)) + return StatusCode(StatusCodes.Status429TooManyRequests, new { error = "Live viewer limit reached" }); + var token = tickets.Issue(cameraId, "read", requester.Id, TicketLifetime, securityStamp, sessionId); + return Ok(new { url = whep.TrimEnd('/') + "/" + cameraId.ToString("D") + "/whep", token, sessionId, + expiresAt = DateTimeOffset.UtcNow.Add(TicketLifetime), iceServers = ReadIceServers() }); + } + + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpDelete("cameras/{cameraId:guid}/session/{sessionId:guid}")] + public async Task ReleaseReadSession(Guid cameraId, Guid sessionId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + sessions.Release(sessionId, cameraId, requester.Id); + return NoContent(); + } + + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPost("agents/{agentId:guid}/cameras/{cameraId:guid}/publish-session")] + public async Task CreatePublishSession(Guid agentId, Guid cameraId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Agent || requester.Id != agentId || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + var url = configuration["LiveMedia:PublishRtspUrl"]; + if (!Uri.TryCreate(url, UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("rtsps" or "rtsp") || + !string.IsNullOrEmpty(endpoint.UserInfo) || !string.IsNullOrEmpty(endpoint.Query) || + !string.IsNullOrEmpty(endpoint.Fragment) || endpoint.AbsolutePath is not ("" or "/")) + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "Live media publishing is not configured" }); + if (endpoint.Scheme != "rtsps" && !configuration.GetValue("LiveMedia:AllowInsecureRtsp")) + return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "Encrypted RTSP publishing is required" }); + var camera = await db.Cameras.AsNoTracking().Where(c => c.Id == cameraId) + .Select(c => new { c.AgentId, c.Status }).SingleOrDefaultAsync(ct); + if (camera is null || camera.AgentId != agentId || camera.Status != CameraStatus.Online) return Conflict(); + var token = tickets.Issue(cameraId, "publish", agentId, TicketLifetime); + var builder = new UriBuilder(endpoint) { Path = cameraId.ToString("D"), Query = "token=" + Uri.EscapeDataString(token) }; + return Ok(new { url = builder.Uri.ToString(), renewAt = DateTimeOffset.UtcNow.AddMinutes(8) }); + } + + // MediaMTX calls this endpoint for each RTSP publish and WHEP read. It is + // intentionally anonymous at ASP.NET level; only an unexpired protected + // ticket with an exact camera/action/path/protocol is accepted. + [AllowAnonymous] + [RequestSizeLimit(16_384)] + [HttpPost("auth")] + public async Task AuthorizeMedia([FromBody] AuthRequest request, CancellationToken ct) + { + var token = string.IsNullOrEmpty(request.Token) ? request.Password : request.Token; + if (!tickets.TryValidateRequest(token, request.Path, request.Action, request.Protocol, out var ticket) || ticket is null) + return Unauthorized(); + + var publish = ticket.Action == "publish" && + await db.Cameras.AsNoTracking().AnyAsync(c => c.Id == ticket.CameraId && c.AgentId == ticket.SubjectId && + c.Status == CameraStatus.Online, ct); + var read = ticket.Action == "read" && + await db.Cameras.AsNoTracking().AnyAsync(c => c.Id == ticket.CameraId && c.Status == CameraStatus.Online, ct) && + await cameraAccess.HasCameraAccessAsync(ticket.SubjectId, ticket.CameraId, ct); + if (read) + { + read = ticket.SessionId is Guid sessionId && sessions.IsActive(sessionId, ticket.CameraId, ticket.SubjectId); + if (!read) return Unauthorized(); + var session = await identity.GetSessionRecordAsync(ticket.SubjectId, ct); + read = session is not null && session.SecurityStamp == ticket.SecurityStamp && + !(session.LockoutEnabled && session.LockoutEnd > DateTimeOffset.UtcNow); + if (read && await db.AppSettings.AsNoTracking().AnyAsync(s => s.Key == "email.confirmation.required" && s.Value == "true", ct)) + read = session!.EmailConfirmed; + } + if (!publish && !read) return Unauthorized(); + var expiry = publish ? DateTimeOffset.UtcNow.AddMinutes(10) : sessions.GetExpiresAt(ticket.SessionId!.Value, ticket.CameraId, ticket.SubjectId); + if (expiry is null || expiry <= DateTimeOffset.UtcNow) return Unauthorized(); + return Ok(new { expireAt = expiry.Value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture) }); + } + + private object[] ReadIceServers() + { + var servers = configuration.GetSection("LiveMedia:IceServers").GetChildren() + .Select(c => c.GetSection("Urls").Get() ?? (c["Urls"] is { } u ? [u] : [])) + .Where(urls => urls.Length > 0 && urls.All(IsIceUrl)).Select(urls => (object)new { urls }) + .ToList(); + var turnUrls = configuration.GetSection("LiveMedia:Turn:Urls").Get() ?? []; + if (turnUrls.Any(url => !IsIceUrl(url) || !(url.StartsWith("turn:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("turns:", StringComparison.OrdinalIgnoreCase)))) turnUrls = []; + var sharedSecret = configuration["LiveMedia:Turn:SharedSecret"]; + if (turnUrls.Length > 0 && !string.IsNullOrWhiteSpace(sharedSecret)) + { + var expiry = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds(); + var username = $"{expiry}:{Guid.NewGuid():N}"; + var key = Encoding.UTF8.GetBytes(sharedSecret); + // Coturn's TURN REST shared-secret authentication specifies HMAC-SHA1; this is protocol compatibility, not a general-purpose signature. +#pragma warning disable CA5350 + var credential = Convert.ToBase64String(HMACSHA1.HashData(key, Encoding.UTF8.GetBytes(username))); +#pragma warning restore CA5350 + servers.Add(new { urls = turnUrls, username, credential }); + } + return servers.ToArray(); + } + + private static bool IsIceUrl(string url) => url.StartsWith("stun:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("stuns:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("turn:", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("turns:", StringComparison.OrdinalIgnoreCase); +} diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 6558233..bcd7fc9 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -1,4 +1,4 @@ - + @@ -4087,4 +4087,8 @@ Duration Size Play +Live + Watch live + Stop live + Live view is unavailable. Check the media service and camera access. diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 413d4a4..4dcbbdf 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -1,4 +1,4 @@ - + @@ -4087,4 +4087,8 @@ Durée Taille Lire +En direct + Voir en direct + Arrêter le direct + Le direct est indisponible. Vérifiez le service média et les droits caméra. diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index b98051f..c47dcd8 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -1,4 +1,4 @@ - + @@ -4087,4 +4087,8 @@ Duration Size Play +Live + Watch live + Stop live + Live view is unavailable. Check the media service and camera access. diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index c4aed75..c07f913 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -514,6 +514,8 @@ public partial class Program private static void ConfigureControllers(WebApplicationBuilder builder) { builder.Services.AddScoped(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddControllers(options => { diff --git a/src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs b/src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs new file mode 100644 index 0000000..e76fb63 --- /dev/null +++ b/src/Heimdall.Web/Security/LiveMediaSessionLimiter.cs @@ -0,0 +1,72 @@ +using Heimdall.Application.Metrics; + +namespace Heimdall.Api.Security; + +/// Bounds active viewer reservations per camera and user with expiry as a disconnect fallback. +public sealed class LiveMediaSessionLimiter +{ + private const int CameraLimit = 8; + private const int UserLimit = 2; + private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10); + private readonly object _gate = new(); + private readonly Dictionary _sessions = []; + private sealed record Reservation(Guid CameraId, Guid UserId, DateTimeOffset ExpiresAt); + + public bool TryAcquire(Guid cameraId, Guid userId, out Guid sessionId) + { + lock (_gate) + { + Prune(); + if (_sessions.Values.Count(s => s.CameraId == cameraId) >= CameraLimit || + _sessions.Values.Count(s => s.UserId == userId) >= UserLimit) + { + sessionId = Guid.Empty; + return false; + } + sessionId = Guid.NewGuid(); + _sessions.Add(sessionId, new Reservation(cameraId, userId, DateTimeOffset.UtcNow.Add(Lifetime))); + HeimdallMetrics.ViewerAdded(); + return true; + } + } + + public bool IsActive(Guid sessionId, Guid cameraId, Guid userId) + { + lock (_gate) + { + Prune(); + return _sessions.TryGetValue(sessionId, out var value) && value.CameraId == cameraId && value.UserId == userId; + } + } + + public DateTimeOffset? GetExpiresAt(Guid sessionId, Guid cameraId, Guid userId) + { + lock (_gate) + { + Prune(); + return _sessions.TryGetValue(sessionId, out var value) && value.CameraId == cameraId && value.UserId == userId + ? value.ExpiresAt : null; + } + } + + public bool Release(Guid sessionId, Guid cameraId, Guid userId) + { + lock (_gate) + { + if (!_sessions.TryGetValue(sessionId, out var value) || value.CameraId != cameraId || value.UserId != userId || + !_sessions.Remove(sessionId)) return false; + HeimdallMetrics.ViewerRemoved(); + return true; + } + } + + private void Prune() + { + var now = DateTimeOffset.UtcNow; + foreach (var id in _sessions.Where(pair => pair.Value.ExpiresAt <= now).Select(pair => pair.Key).ToArray()) + { + _sessions.Remove(id); + HeimdallMetrics.ViewerRemoved(); + } + } +} diff --git a/src/Heimdall.Web/Security/LiveMediaTickets.cs b/src/Heimdall.Web/Security/LiveMediaTickets.cs new file mode 100644 index 0000000..45d758e --- /dev/null +++ b/src/Heimdall.Web/Security/LiveMediaTickets.cs @@ -0,0 +1,55 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; + +namespace Heimdall.Api.Security; + +public sealed record LiveMediaTicket(Guid CameraId, string Action, Guid SubjectId, DateTimeOffset ExpiresAt, + string? SecurityStamp = null, Guid? SessionId = null); + +/// Issues purpose-bound, time-limited tickets for the MediaMTX auth callback. +public sealed class LiveMediaTickets +{ + private readonly ITimeLimitedDataProtector _protector; + public LiveMediaTickets(IDataProtectionProvider provider) => + _protector = provider.CreateProtector("Heimdall.LiveMedia.v1").ToTimeLimitedDataProtector(); + + public string Issue(Guid cameraId, string action, Guid subjectId, TimeSpan lifetime, string? securityStamp = null, Guid? sessionId = null) + { + if (cameraId == Guid.Empty || subjectId == Guid.Empty || lifetime <= TimeSpan.Zero || lifetime > TimeSpan.FromMinutes(5)) + throw new ArgumentOutOfRangeException(nameof(lifetime)); + var ticket = new LiveMediaTicket(cameraId, action, subjectId, DateTimeOffset.UtcNow.Add(lifetime), securityStamp, sessionId); + return _protector.Protect(JsonSerializer.Serialize(ticket), lifetime); + } + + public bool TryRead(string? token, out LiveMediaTicket? ticket) + { + ticket = null; + if (string.IsNullOrWhiteSpace(token) || token.Length > 4096) return false; + try + { + var json = _protector.Unprotect(token, out _); + ticket = JsonSerializer.Deserialize(json); + return ticket is not null && ticket.CameraId != Guid.Empty && + ticket.SubjectId != Guid.Empty && ticket.ExpiresAt > DateTimeOffset.UtcNow; + } + catch (CryptographicException) { return false; } + catch (JsonException) { return false; } + } + + public bool TryValidateRequest(string? token, string? path, string? action, string? protocol, + out LiveMediaTicket? ticket) + { + if (!TryRead(token, out ticket) || ticket is null || + !string.Equals(path, ticket.CameraId.ToString("D"), StringComparison.OrdinalIgnoreCase) || + !string.Equals(ticket.Action, action, StringComparison.Ordinal) || + ticket.Action is not ("publish" or "read") || + (ticket.Action == "publish" && protocol != "rtsp") || + (ticket.Action == "read" && protocol != "webrtc")) + { + ticket = null; + return false; + } + return true; + } +} diff --git a/src/Heimdall.Web/wwwroot/js/live-view.js b/src/Heimdall.Web/wwwroot/js/live-view.js new file mode 100644 index 0000000..f297a07 --- /dev/null +++ b/src/Heimdall.Web/wwwroot/js/live-view.js @@ -0,0 +1,44 @@ +const active = new Map(); +async function gather(pc) { + if (pc.iceGatheringState === "complete") return; + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error("ICE gathering timeout")), 10000); + pc.addEventListener("icegatheringstatechange", () => { + if (pc.iceGatheringState === "complete") { clearTimeout(timeout); resolve(); } + }); + }); +} +export async function start(cameraId, video) { + await stop(cameraId); + const r = await fetch(`/api/live-media/cameras/${cameraId}/session`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: "{}" }); + if (!r.ok) throw new Error("Live session is unavailable"); + const s = await r.json(); + const pc = new RTCPeerConnection({ iceServers: s.iceServers || [] }); + const state = { pc, token: s.token, url: s.url, sessionId: s.sessionId, resource: null }; + active.set(cameraId, state); + pc.addTransceiver("video", { direction: "recvonly" }); + pc.ontrack = e => { + video.srcObject = e.streams[0]; + video.play().catch(() => {}); + e.track.addEventListener("ended", () => void stop(cameraId), { once: true }); + }; + try { + await pc.setLocalDescription(await pc.createOffer()); + await gather(pc); + const answer = await fetch(s.url, { method: "POST", headers: { Authorization: `Bearer ${s.token}`, "Content-Type": "application/sdp", Accept: "application/sdp" }, body: pc.localDescription.sdp }); + if (!answer.ok) throw new Error("WHEP negotiation failed"); + const location = answer.headers.get("Location"); + state.resource = location ? new URL(location, s.url).toString() : null; + await pc.setRemoteDescription({ type: "answer", sdp: await answer.text() }); + } catch (e) { await stop(cameraId); throw e; } +} +export async function stop(cameraId) { + const s = active.get(cameraId); + if (!s) return; + active.delete(cameraId); + s.pc.close(); + if (s.resource) { try { await fetch(s.resource, { method: "DELETE", headers: { Authorization: `Bearer ${s.token}` } }); } catch { } } + try { await fetch(`/api/live-media/cameras/${cameraId}/session/${s.sessionId}`, { method: "DELETE", credentials: "same-origin" }); } catch { } + const v = document.querySelector(`[data-live-camera="${cameraId}"]`); + if (v) v.srcObject = null; +} diff --git a/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs new file mode 100644 index 0000000..1086cd9 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs @@ -0,0 +1,32 @@ +using Heimdall.Agent.Services; + +namespace Heimdall.Agent.Tests; + +public sealed class LiveCameraRelayServiceTests +{ + [Fact] + public void Uses_only_enabled_Rtsp_cameras_from_authoritative_Central_assignment_and_caps_publishers() + { + var store = new CameraConfigStore(); + var fallback = new AgentCameraConfig(Guid.NewGuid(), "fallback", "rtsp://127.0.0.1/fallback", null, true); + store.SetLocalFallback([fallback]); + Assert.Empty(LiveCameraRelayService.SelectAssignedCameras(store)); + + var settings = new Dictionary(); + for (var i = 0; i < 3; i++) + { + var id = Guid.NewGuid(); + settings[$"camera.{id}.rtsp"] = $"rtsp://127.0.0.1/{i}"; + settings[$"camera.{id}.enabled"] = i == 2 ? "false" : "true"; + } + var invalidId = Guid.NewGuid(); + settings[$"camera.{invalidId}.rtsp"] = "file:///etc/passwd"; + settings[$"camera.{invalidId}.enabled"] = "true"; + store.ReplaceCentral(settings); + + var selected = LiveCameraRelayService.SelectAssignedCameras(store); + Assert.Equal(2, selected.Count); + Assert.DoesNotContain(fallback.CameraId, selected.Keys); + Assert.DoesNotContain(invalidId, selected.Keys); + } +} diff --git a/tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs b/tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs new file mode 100644 index 0000000..e540a5a --- /dev/null +++ b/tests/Heimdall.Api.Tests/LiveMediaSessionLimiterTests.cs @@ -0,0 +1,33 @@ +using Heimdall.Api.Security; + +namespace Heimdall.Api.Tests; + +public sealed class LiveMediaSessionLimiterTests +{ + [Fact] + public void Viewer_slots_are_camera_and_user_scoped_and_released_by_owner() + { + var limiter = new LiveMediaSessionLimiter(); + var camera = Guid.NewGuid(); + var user = Guid.NewGuid(); + var sessions = new List(); + for (var i = 0; i < 2; i++) + { + Assert.True(limiter.TryAcquire(camera, user, out var session)); + sessions.Add(session); + } + Assert.False(limiter.TryAcquire(Guid.NewGuid(), user, out _)); + Assert.False(limiter.Release(sessions[0], camera, Guid.NewGuid())); + Assert.True(limiter.Release(sessions[0], camera, user)); + Assert.True(limiter.TryAcquire(camera, user, out _)); + } + + [Fact] + public void Camera_limit_bounds_concurrent_viewers() + { + var limiter = new LiveMediaSessionLimiter(); + var camera = Guid.NewGuid(); + for (var i = 0; i < 8; i++) Assert.True(limiter.TryAcquire(camera, Guid.NewGuid(), out _)); + Assert.False(limiter.TryAcquire(camera, Guid.NewGuid(), out _)); + } +} diff --git a/tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs b/tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs new file mode 100644 index 0000000..c30157f --- /dev/null +++ b/tests/Heimdall.Api.Tests/LiveMediaTicketsTests.cs @@ -0,0 +1,52 @@ +using Heimdall.Api.Security; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; + +namespace Heimdall.Api.Tests; + +public sealed class LiveMediaTicketsTests +{ + private static LiveMediaTickets CreateTickets() + { + var services = new ServiceCollection(); + services.AddDataProtection().SetApplicationName("Heimdall.LiveMedia.Tests"); + return new LiveMediaTickets(services.BuildServiceProvider().GetRequiredService()); + } + + [Fact] + public void Ticket_is_valid_and_camera_scoped() + { + var tickets = CreateTickets(); + var camera = Guid.NewGuid(); + var agent = Guid.NewGuid(); + var token = tickets.Issue(camera, "publish", agent, TimeSpan.FromMinutes(2)); + + Assert.True(tickets.TryRead(token, out var ticket)); + Assert.Equal(camera, ticket!.CameraId); + Assert.Equal(agent, ticket.SubjectId); + Assert.Equal("publish", ticket.Action); + } + + [Fact] + public void Ticket_rejects_tampering_and_invalid_lifetime() + { + var tickets = CreateTickets(); + var token = tickets.Issue(Guid.NewGuid(), "read", Guid.NewGuid(), TimeSpan.FromMinutes(1)); + + Assert.False(tickets.TryRead(token + "x", out _)); + Assert.Throws(() => tickets.Issue(Guid.NewGuid(), "read", Guid.NewGuid(), TimeSpan.FromMinutes(6))); + } + + [Fact] + public void Publish_claim_is_bound_to_exact_path_action_and_protocol() + { + var tickets = CreateTickets(); + var camera = Guid.NewGuid(); + var token = tickets.Issue(camera, "publish", Guid.NewGuid(), TimeSpan.FromMinutes(1)); + + Assert.True(tickets.TryValidateRequest(token, camera.ToString("D"), "publish", "rtsp", out _)); + Assert.False(tickets.TryValidateRequest(token, Guid.NewGuid().ToString("D"), "publish", "rtsp", out _)); + Assert.False(tickets.TryValidateRequest(token, camera.ToString("D"), "read", "webrtc", out _)); + Assert.False(tickets.TryValidateRequest(token, camera.ToString("D"), "publish", "webrtc", out _)); + } +} diff --git a/todo.md b/todo.md index 91891c9..1da5a00 100644 --- a/todo.md +++ b/todo.md @@ -45,7 +45,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. -- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. Un vertical initial ajoute le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read Data Protection à durée limitée, la revalidation des droits caméra et un lecteur WHEP dans le détail caméra ; audio/PTZ restent exclus. Les builds/tests ciblés API/Web (7 tests) et Agent (1 test), la syntaxe JS et `git diff --check` passent. La recette Compose jetable a validé bootstrap admin/site, enregistrement Agent, caméra RTSP synthétique assignée/activée, demande publish-session et démarrage du relais, ticket read autorisé + callback MediaMTX 200, rejet ticket forgé 401 et rejet caméra inconnue. Une requête WHEP avec SDP invalide a atteint MediaMTX et retourné 400; aucun navigateur/frame décodée ni arrêt par désactivation API n’a été vérifié. Compose `hmd-webrtc-e9e542` a été arrêté avec `down --volumes --remove-orphans`, puis ses conteneurs, volumes et réseaux vérifiés absents; les secrets/cache acceptance ont été supprimés. Validation caméra physique, LAN, TURN externe, lecture d’une vraie offre SDP et cycle désactivation restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt. Test d'inférence ONNX CPU 1080p autonome : 1/1. Restent image/runtime GPU, sélection UI/installateur, manifeste de release, test complet et matériel CUDA réel. @@ -53,7 +53,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** L'édition des groupes permet maintenant de lister les caméras des sites, d'accorder/révoquer les accès de groupe et d'afficher les noms de site/caméra via l'API existante. Restent la validation produit et la vérification de l'union accès direct/groupe ainsi que des priorités dans l'interface. - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. -- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers existe, mais aucun producteur WebRTC n'existe avant FEAT-01. Restent la validation de scraping sur un déploiement et l'évolution réelle des mesures. +- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; reste une validation de scraping sur un déploiement et l'évolution réelle des mesures. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Restent la validation des seuils sur déploiement et les pannes à valider sur déploiement réel. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. - [ ] Actualiser les guides après chaque changement d'infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Vérifier une installation depuis la documentation. -- 2.54.1 From 5c52c0e8f9c2ecbb9a980bffee650e140f58c4aa Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 22:41:05 +0100 Subject: [PATCH 13/40] feat(agent): add optional pinned CUDA deployment variant --- .gitea/workflows/build.yml | 41 +++++++++- docker/Dockerfile.agent.gpu | 31 ++++++++ .../docker-compose.agent.dev.gpu-nvidia.yml | 21 +++++ docker/docker-compose.gpu-nvidia.yml | 4 +- docs/agent-release-signing.md | 4 +- docs/gitea-builds.md | 4 +- docs/gpu-runtime.md | 67 +++++++--------- scripts/ci/accept-release-offline.py | 43 +++++++++-- scripts/ci/images.sh | 7 +- scripts/ci/publish.sh | 27 ++++++- scripts/ci/push-images.sh | 5 +- scripts/ci/security.sh | 4 +- scripts/ci/test_ci.py | 26 +++++++ scripts/ci/validate-compose.sh | 4 + skills/gpu-inference/SKILL.md | 6 +- src/Heimdall.Agent/Heimdall.Agent.csproj | 1 + .../Services/DockerUpdateService.cs | 21 ++++- .../Services/ReleaseSignatureVerifier.cs | 8 +- src/Heimdall.Agent/packages.gpu.lock.json | 37 +++++++++ .../Components/SiteInstallPanel.razor | 35 ++++++++- .../Controllers/UpdatesController.cs | 12 ++- .../Localization/SharedResources.en.resx | 6 ++ .../Localization/SharedResources.fr.resx | 6 ++ .../Localization/SharedResources.resx | 6 ++ .../Services/HeimdallApiClient.cs | 2 +- .../Heimdall.Agent.Tests.csproj | 1 + .../Services/ReleaseSignatureVerifierTests.cs | 42 ++++++++++ .../packages.gpu.lock.json | 57 ++++++++++++++ .../Components/Pages/SiteDetailTests.cs | 77 +++++++++++++++++++ .../Heimdall.Web.Tests.csproj | 1 + tests/Heimdall.Web.Tests/packages.lock.json | 10 ++- todo.md | 2 +- 32 files changed, 537 insertions(+), 81 deletions(-) create mode 100644 docker/Dockerfile.agent.gpu create mode 100644 docker/docker-compose.agent.dev.gpu-nvidia.yml create mode 100644 tests/Heimdall.Agent.Tests/Services/ReleaseSignatureVerifierTests.cs diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 0251a19..fe8a2d3 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -75,7 +75,7 @@ jobs: policy: name: CI policy if: always() - needs: [changes, verify, server_image, agent_image, dockerhub_latest, publish] + needs: [changes, verify, server_image, agent_image, agent_gpu_image, dockerhub_latest, publish] runs-on: [ubuntu-latest, build-agent] steps: - name: Require all applicable validation jobs to pass @@ -85,6 +85,7 @@ jobs: VERIFY_RESULT: ${{ needs.verify.result }} SERVER_IMAGE_RESULT: ${{ needs.server_image.result }} AGENT_IMAGE_RESULT: ${{ needs.agent_image.result }} + AGENT_GPU_IMAGE_RESULT: ${{ needs.agent_gpu_image.result }} DOCKERHUB_RESULT: ${{ needs.dockerhub_latest.result }} RELEASE_RESULT: ${{ needs.publish.result }} EVENT_NAME: ${{ gitea.event_name }} @@ -103,10 +104,12 @@ jobs: pull_request:*) test "$SERVER_IMAGE_RESULT" = success test "$AGENT_IMAGE_RESULT" = success + test "$AGENT_GPU_IMAGE_RESULT" = success ;; push:refs/heads/main) test "$SERVER_IMAGE_RESULT" = success test "$AGENT_IMAGE_RESULT" = success + test "$AGENT_GPU_IMAGE_RESULT" = success test "$DOCKERHUB_RESULT" = success ;; push:refs/tags/v*) @@ -286,6 +289,42 @@ jobs: if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then bash scripts/ci/cleanup-docker.sh after fi + agent_gpu_image: + name: Build and scan NVIDIA Agent image + if: needs.changes.outputs.run_validation == 'true' && (gitea.event_name == 'pull_request' || gitea.ref == 'refs/heads/main') + needs: [changes, verify] + runs-on: [ubuntu-latest, build-agent] + container: + image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b + steps: + - name: Prepare action runtime before checkout + run: | + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils + test "$(uname -m)" = x86_64 + curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz + echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check + tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1 + ln -sf /usr/local/bin/node /usr/bin/node + rm /tmp/node.tar.xz + - name: Checkout + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - name: Runner prerequisites + run: bash scripts/ci/bootstrap.sh + - name: Reclaim old build storage + run: bash scripts/ci/cleanup-docker.sh before + - name: Build NVIDIA Agent image + run: bash scripts/ci/images.sh agent-gpu + - name: Scan NVIDIA Agent image + run: bash scripts/ci/security.sh agent-gpu + - name: Reclaim build storage after job + if: always() + run: | + if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then + bash scripts/ci/cleanup-docker.sh after + fi dockerhub_latest: name: Publish Docker Hub latest tags if: needs.changes.outputs.run_validation == 'true' && gitea.ref == 'refs/heads/main' diff --git a/docker/Dockerfile.agent.gpu b/docker/Dockerfile.agent.gpu new file mode 100644 index 0000000..d186776 --- /dev/null +++ b/docker/Dockerfile.agent.gpu @@ -0,0 +1,31 @@ +# Optional NVIDIA Agent image. ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9. +# NVIDIA amd64 runtime image digest is pinned; it includes CUDA 12.8.1/cuDNN 9.8.0.87. +FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build +WORKDIR /src +ARG VERSION=0.0.0-local +COPY global.json Directory.Build.props Directory.Build.targets ./ +COPY src/ ./src/ +RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode +RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out \ + -p:HeimdallOnnxRuntime=GPU -p:Version=$VERSION -p:ContinuousIntegrationBuild=true + +FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee AS dotnet-runtime + +FROM --platform=linux/amd64 nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime +WORKDIR /app +ENV DOTNET_ROOT=/usr/share/dotnet \ + PATH=/usr/share/dotnet:$PATH \ + LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu \ + ASPNETCORE_URLS=http://127.0.0.1:8080 \ + Agent__InferenceExecutionProvider=CUDA +RUN apt-get update -qq && apt-get install -y --no-install-recommends \ + ca-certificates ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \ + && rm -rf /var/lib/apt/lists/* \ + && install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall +COPY --from=dotnet-runtime /usr/share/dotnet/ /usr/share/dotnet/ +COPY --from=build /out/ ./ +COPY models/yolov8n.onnx ./models/yolov8n.onnx +EXPOSE 8080 +HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q --spider http://127.0.0.1:8080/healthz || exit 1 +USER 1654:1654 +ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"] diff --git a/docker/docker-compose.agent.dev.gpu-nvidia.yml b/docker/docker-compose.agent.dev.gpu-nvidia.yml new file mode 100644 index 0000000..7b7a2cd --- /dev/null +++ b/docker/docker-compose.agent.dev.gpu-nvidia.yml @@ -0,0 +1,21 @@ +# Optional development overlay. The default dev Compose remains CPU-only. +services: + heimdall-agent: + profiles: + - gpu-nvidia + image: heimdall-agent:gpu-local + build: + context: .. + dockerfile: docker/Dockerfile.agent.gpu + environment: + Agent__InferenceExecutionProvider: CUDA + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] + + agent-state-init: + image: heimdall-agent:local diff --git a/docker/docker-compose.gpu-nvidia.yml b/docker/docker-compose.gpu-nvidia.yml index 59eb703..d362d6e 100644 --- a/docker/docker-compose.gpu-nvidia.yml +++ b/docker/docker-compose.gpu-nvidia.yml @@ -1,5 +1,5 @@ -# Optional NVIDIA device passthrough for Agent GPU inventory. -# The current Agent image still runs ONNX inference on CPU. +# Optional NVIDIA device passthrough for Agent GPU inventory on the published +# CPU image. Use docker-compose.agent.dev.gpu-nvidia.yml for the CUDA image. services: heimdall-agent: profiles: diff --git a/docs/agent-release-signing.md b/docs/agent-release-signing.md index caccf04..b5e7bcb 100644 --- a/docs/agent-release-signing.md +++ b/docs/agent-release-signing.md @@ -16,7 +16,7 @@ La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant toute publication. Les images serveur et Agent sont publiées sur Docker Hub sous `eltruncho/heimdall` et `eltruncho/heimdall-agent`; configurer les secrets Actions `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN`. Central transmet à l’Agent le dépôt et le digest signés dans la release. -La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent et le dépôt ainsi que le digest immuable de l’image Docker. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé. +La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent ces références et leur SHA-256 est listé dans `SHA256SUMS`. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé. Les mises à jour automatiques natives sont désactivées par défaut dans les réglages globaux Agent; chaque site peut hériter de ce réglage ou le remplacer. L’Agent vérifie les releases toutes les 12 heures et attend que `publishedAt` ait au moins 24 heures avant d’appliquer une mise à jour automatique. Une demande manuelle d’administrateur peut déclencher la mise à jour immédiatement. Les installations Docker/Kubernetes ne font pas de polling d’image local : elles suivent le mécanisme de l’orchestrateur et le digest fourni par l’IHM. @@ -35,7 +35,7 @@ L’installateur Linux est servi par Central avec son superviseur. Il installe l Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution. -Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. +Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour. ## Rotation diff --git a/docs/gitea-builds.md b/docs/gitea-builds.md index 7fc1c77..389d99f 100644 --- a/docs/gitea-builds.md +++ b/docs/gitea-builds.md @@ -1,6 +1,6 @@ # CI Gitea et images Heimdall -La chaîne active est `.gitea/workflows/build.yml`. Chaque PR lance le job léger `CI policy`, qui détecte les fichiers concernés. Si seuls la documentation ou les fichiers hors périmètre changent, les builds, tests, images et scans sont ignorés ; sinon ils s'exécutent avant que la politique réussisse. Les PR qui touchent le code valident la compilation, les suites .NET concernées, les archives, les images CPU amd64 et les contrôles de sécurité. Le job `verify` compile, teste et contrôle les dépendances NuGet. Les jobs `server_image` et `agent_image` construisent et scannent leurs images séparément après `verify` ; ils peuvent tourner en parallèle sur deux runners autorisés. `CI policy` doit être configuré comme contrôle obligatoire de `main`. Les pushes sur `main` restent filtrés par chemins et les tags `v*` gardent leur parcours complet : ils exécutent toutes les suites et le job de release reconstruit les images de version. +La chaîne active est `.gitea/workflows/build.yml`. Chaque PR lance le job léger `CI policy`, qui détecte les fichiers concernés. Si seuls la documentation ou les fichiers hors périmètre changent, les builds, tests, images et scans sont ignorés ; sinon ils s'exécutent avant que la politique réussisse. Les PR qui touchent le code valident la compilation, les suites .NET concernées, les archives, les images CPU amd64 et le build/scan de l’image Agent CUDA optionnelle, sans exiger de matériel GPU. Le job `verify` compile, teste et contrôle les dépendances NuGet. Les jobs `server_image`, `agent_image` et `agent_gpu_image` construisent et scannent leurs images séparément après `verify` ; ils peuvent tourner en parallèle sur des runners autorisés. `CI policy` doit être configuré comme contrôle obligatoire de `main`. Les pushes sur `main` restent filtrés par chemins et les tags `v*` gardent leur parcours complet : ils exécutent toutes les suites et le job de release reconstruit les images de version. ## Sélection des runners @@ -25,7 +25,7 @@ Après validation de `verify` sur `main`, chaque job d'image publie son tag immu Aucun tag Git n'est requis. Les PR ne reçoivent pas de secret de publication et ne poussent aucune image. Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets d'organisation `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN` doivent être disponibles ; le token doit autoriser l'écriture dans les deux dépôts Docker Hub. Les identifiants sont transmis par stdin à `docker login` et stockés seulement dans une configuration temporaire supprimée en sortie. -Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` conservent le job séparé de release, après validation de `verify`. Le job reconstruit les archives depuis le commit vérifié et prépare la publication signée. Il nécessite en plus `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`. La release reste en brouillon jusqu'à promotion explicite. +Les tags Git `vMAJOR.MINOR.PATCH[-prerelease]` conservent le job séparé de release, après validation de `verify`. Le job reconstruit et scanne les trois images, puis publie les images CPU et CUDA de l’Agent et joint leurs manifestes au manifeste ECDSA signé. Il nécessite en plus `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN`, `RELEASE_TOKEN` et `RELEASE_SIGNING_KEY_B64`. La release reste en brouillon jusqu'à promotion explicite. ## Renovate diff --git a/docs/gpu-runtime.md b/docs/gpu-runtime.md index d03cf7f..376c02d 100644 --- a/docs/gpu-runtime.md +++ b/docs/gpu-runtime.md @@ -1,47 +1,32 @@ # GPU device access and inference status -The default Agent uses `CPUExecutionProvider`. The published Agent image only -contains the CPU ONNX Runtime package. `Agent__InferenceExecutionProvider` -accepts `CPU` (the default) or `CUDA`; the current published image does not -include the CUDA provider or its CUDA/cuDNN runtime libraries. A CUDA request in -that image is logged and falls back to CPU. GPU detection and inventory report -host hardware; they do not mean that frame inference is running on that -hardware. +The default Agent image and install path use `CPUExecutionProvider` and do not +require NVIDIA. The optional amd64 CUDA image is built from +`docker/Dockerfile.agent.gpu` and published as `eltruncho/heimdall-agent-gpu`. +Its immutable image digest is stored in the signed `agent-image-gpu.json` +release asset. Central offers the NVIDIA install option when that signed +release metadata is present. Existing Agent Compose files remain CPU-only. -The production Agent Compose is generated in Central's UI. Save that file as -`docker-compose.yml` on the camera host. To expose hardware for inventory, -copy the matching optional overlay from this repository beside it, then run: +ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9. The optional image pins NVIDIA +`12.8.1-cudnn-runtime-ubuntu24.04` to amd64 manifest +`sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9` and +uses the separate locked GPU NuGet dependency graph. See the [ONNX Runtime CUDA +provider compatibility table](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html) +and [NVIDIA CUDA image tag](https://hub.docker.com/r/nvidia/cuda/tags?name=12.8.1-cudnn-runtime-ubuntu24.04). -```sh -# NVIDIA -docker compose \ - -f docker-compose.yml \ - -f docker-compose.gpu-nvidia.yml \ - --profile gpu-nvidia-inventory up -d heimdall-agent +The installer sets `Agent__InferenceExecutionProvider=CUDA` and requests all +NVIDIA devices for that variant. CUDA initialization failure logs a warning +and falls back to CPU. A physical GPU, compatible host driver and NVIDIA +Container Toolkit are required; see the [NVIDIA Container Toolkit install guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). -# AMD ROCm devices -docker compose \ - -f docker-compose.yml \ - -f docker-compose.gpu-amd.yml \ - --profile gpu-amd-inventory up -d heimdall-agent +The `docker-compose.gpu-{nvidia,amd,intel}.yml` files remain inventory-only +overlays. For local development, the CPU default is +`docker/docker-compose.agent.dev.yml`; use +`docker/docker-compose.agent.dev.gpu-nvidia.yml` with `--profile gpu-nvidia` to +select the opt-in CUDA runtime. Intel and AMD inventory hosts may need +`VIDEO_GID` and `RENDER_GID` set to host group IDs that can access `/dev/dri`. -# Intel render device -docker compose \ - -f docker-compose.yml \ - -f docker-compose.gpu-intel.yml \ - --profile gpu-intel-inventory up -d heimdall-agent -``` - -For local development, use the same overlay with -`docker/docker-compose.agent.dev.yml`. For Intel and AMD hosts, set `VIDEO_GID` and `RENDER_GID` to -the host group IDs that can access `/dev/dri`. The NVIDIA option requires the -NVIDIA Container Toolkit and Docker Compose GPU device reservations. - -These overlays only expose devices for Agent inventory. They do not enable -GPU-accelerated ONNX inference. The Agent project has an opt-in GPU package -restore/build variant (`-p:HeimdallOnnxRuntime=GPU`) for provider/fallback -development, but no GPU runtime image is published or selected by the install -UI yet. Actual GPU inference still requires a compatible CUDA/cuDNN runtime, -host driver access, image publication and installer selection, then validation -on real supported hardware. CPU fallback is covered by local tests; hardware -execution is not. +The image and Compose build acceptance and physical CUDA execution have not +been run for this change. Local tests cover CPU fallback, CPU/GPU installer +configuration and signed CPU/GPU release manifests; hardware execution remains +open. diff --git a/scripts/ci/accept-release-offline.py b/scripts/ci/accept-release-offline.py index 7acb57c..1234820 100755 --- a/scripts/ci/accept-release-offline.py +++ b/scripts/ci/accept-release-offline.py @@ -24,6 +24,7 @@ DOCKER_TOKEN = 'offline-docker-token-not-valid' RELEASE_TOKEN = 'offline-gitea-token-not-valid' SERVER_DIGEST = 'sha256:' + '1' * 64 AGENT_DIGEST = 'sha256:' + '2' * 64 +GPU_AGENT_DIGEST = 'sha256:' + '3' * 64 def run(command, *, cwd, env, label): @@ -77,9 +78,32 @@ if args[:1] == ['push']: sys.exit(0) # Simulated push only; no registry client exists in this stub. if args[:2] == ['image', 'inspect']: image = args[2].split(':', 1)[0] - digest = 'sha256:' + ('2' if image.endswith('heimdall-agent') else '1') * 64 + if image.endswith('heimdall-agent-gpu'): + digest = os.environ['OFFLINE_GPU_DIGEST'] + elif image.endswith('heimdall-agent'): + digest = os.environ['OFFLINE_AGENT_DIGEST'] + else: + digest = os.environ['OFFLINE_SERVER_DIGEST'] print(image + '@' + digest) sys.exit(0) +if args[:1] == ['save']: + from pathlib import Path + Path(args[args.index('-o') + 1]).write_bytes(b'offline-image-archive') + sys.exit(0) +if args[:2] == ['volume', 'create']: + print(args[2]) + sys.exit(0) +if args[:1] == ['create']: + print('offline-scanner-container') + sys.exit(0) +if args[:1] == ['cp'] or args[:1] == ['rm'] or args[:2] == ['volume', 'rm']: + sys.exit(0) +if args[:2] == ['start', '--attach']: + print('{"Results":[]}') + sys.exit(0) +if args[:1] == ['inspect']: + print('exited 0') + sys.exit(0) sys.exit(12) ''' docker_path = fakebin / 'docker' @@ -172,6 +196,9 @@ sys.exit(12) 'RELEASE_TOKEN': RELEASE_TOKEN, 'RELEASE_SIGNING_KEY_B64': signing_key_b64, 'OFFLINE_DOCKER_LOG': str(docker_log), + 'OFFLINE_SERVER_DIGEST': SERVER_DIGEST, + 'OFFLINE_AGENT_DIGEST': AGENT_DIGEST, + 'OFFLINE_GPU_DIGEST': GPU_AGENT_DIGEST, }) run(['bash', 'scripts/ci/package.sh'], cwd=ROOT, env=env, label='package.sh') run(['bash', 'scripts/ci/publish.sh'], cwd=ROOT, env=env, label='publish.sh') @@ -186,11 +213,15 @@ sys.exit(12) assert manifest['version'] == TAG assert manifest['containerImage'] == 'eltruncho/heimdall-agent' assert manifest['containerImageDigest'] == AGENT_DIGEST + assert manifest['containerImageGpu'] == 'eltruncho/heimdall-agent-gpu' + assert manifest['containerImageGpuDigest'] == GPU_AGENT_DIGEST provenance = json.loads(release_state['assets']['provenance.json']) commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip() assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/' + TAG agent_image = json.loads(release_state['assets']['agent-image.json']) assert agent_image == {'digest': AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent'} + gpu_agent_image = json.loads(release_state['assets']['agent-image-gpu.json']) + assert gpu_agent_image == {'digest': GPU_AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent-gpu'} for platform, digest in manifest['assets'].items(): archive = f'heimdall-agent-{platform}-{TAG.removeprefix("v")}.tar.gz' assert hashlib.sha256(release_state['assets'][archive]).hexdigest() == digest @@ -205,21 +236,23 @@ sys.exit(12) assert filename in release_state['assets'], f'missing checksum asset {filename}' assert hashlib.sha256(release_state['assets'][filename]).hexdigest() == digest, filename image_digests = release_state['assets']['image-digests.txt'].decode().splitlines() - assert len(image_digests) == 4 + assert len(image_digests) == 6 assert sum(AGENT_DIGEST in item for item in image_digests) == 2 + assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 2 docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()] - assert sum(call[:1] == ['build'] for call in docker_calls) == 2 + assert sum(call[:1] == ['build'] for call in docker_calls) == 3 pushes = {call[1] for call in docker_calls if call[:1] == ['push']} - assert len(pushes) == 4 + assert len(pushes) == 6 assert pushes == { f'eltruncho/heimdall:sha-{commit}', f'eltruncho/heimdall:1.2.3', f'eltruncho/heimdall-agent:sha-{commit}', f'eltruncho/heimdall-agent:1.2.3', + f'eltruncho/heimdall-agent-gpu:sha-{commit}', f'eltruncho/heimdall-agent-gpu:1.2.3', } assert sum(call[:1] == ['login'] for call in docker_calls) == 1 assert release_state['draft']['draft'] is True assert len(release_state['assets']) >= 9 assert release_state['authorized'] >= 7 - print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} draft assets, checksums, image digests, and four simulated pushes.') + print(f'Offline release simulation passed: package archives, P-256 signature, {len(release_state["assets"])} draft assets, checksums, CPU/GPU image digests, and six simulated pushes.') print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.') finally: server.shutdown() diff --git a/scripts/ci/images.sh b/scripts/ci/images.sh index 2aa6760..c75acf8 100644 --- a/scripts/ci/images.sh +++ b/scripts/ci/images.sh @@ -6,13 +6,14 @@ version=$(cat artifacts/version 2>/dev/null || printf '0.0.0-ci.%s' "${sha:0:12} : "${BUILD_REPOSITORY:?Gitea repository is required}" source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}" case "${1:-all}" in - all) components=(server agent) ;; - server|agent) components=("$1") ;; - *) echo 'Usage: images.sh [server|agent|all]' >&2; exit 2 ;; + all) components=(server agent agent-gpu) ;; + server|agent|agent-gpu) components=("$1") ;; + *) echo 'Usage: images.sh [server|agent|agent-gpu|all]' >&2; exit 2 ;; esac for component in "${components[@]}"; do file=docker/Dockerfile [[ "$component" == agent ]] && file=docker/Dockerfile.agent + [[ "$component" == agent-gpu ]] && file=docker/Dockerfile.agent.gpu docker build --pull --platform linux/amd64 -f "$file" --build-arg "VERSION=$version" \ --label "org.opencontainers.image.revision=$sha" \ --label "org.opencontainers.image.version=$version" \ diff --git a/scripts/ci/publish.sh b/scripts/ci/publish.sh index cc6b13a..fec2a17 100644 --- a/scripts/ci/publish.sh +++ b/scripts/ci/publish.sh @@ -44,19 +44,23 @@ PY (cd artifacts/packages && sha256sum --check SHA256SUMS) printf '%s' "${tag#v}" > artifacts/version bash scripts/ci/images.sh +bash scripts/ci/security.sh agent-gpu # No mutation is attempted until all credentials, provenance and local builds pass. export DOCKER_CONFIG DOCKER_CONFIG=$(mktemp -d) trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT server_image=eltruncho/heimdall agent_image=eltruncho/heimdall-agent +agent_gpu_image=eltruncho/heimdall-agent-gpu : "${DOCKERHUB_USERNAME:?Docker Hub user is required}" : "${DOCKERHUB_TOKEN:?Docker Hub token is required}" printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin : > artifacts/image-digests.txt -for component in server agent; do +for component in server agent agent-gpu; do if [[ "$component" == agent ]]; then image=$agent_image + elif [[ "$component" == agent-gpu ]]; then + image=$agent_gpu_image else image=$server_image fi @@ -91,11 +95,29 @@ with open('artifacts/packages/agent-image.json','w') as f: f.write('\n') PY (cd artifacts/packages && sha256sum agent-image.json >> SHA256SUMS) +python3 - "$agent_gpu_image" <<'PY' +import json,sys +repository=sys.argv[1] +matches=set() +for line in open('artifacts/image-digests.txt'): + ref=line.strip() + if '@' not in ref: continue + image,digest=ref.rsplit('@',1) + if image == repository and digest.startswith('sha256:') and len(digest) == 71: + matches.add(digest) +if len(matches) != 1: + raise SystemExit('Expected one immutable GPU agent image digest for configured repository') +with open('artifacts/packages/agent-image-gpu.json','w') as f: + json.dump({'image':repository,'digest':matches.pop()},f,sort_keys=True,separators=(',',':')) + f.write('\n') +PY +(cd artifacts/packages && sha256sum agent-image-gpu.json >> SHA256SUMS) python3 - <<'PY' import hashlib,json,re from pathlib import Path root=Path('artifacts/packages') image=json.loads((root/'agent-image.json').read_text()) +gpu_image=json.loads((root/'agent-image-gpu.json').read_text()) package_version=Path('artifacts/version').read_text().strip() version='v'+package_version assets={} @@ -110,7 +132,8 @@ for path in root.glob('heimdall-agent-*.tar.gz'): if not assets: raise SystemExit('No agent archive to sign') payload={'version':version,'assets':assets,'containerImage':image['image'], - 'containerImageDigest':image['digest']} + 'containerImageDigest':image['digest'],'containerImageGpu':gpu_image['image'], + 'containerImageGpuDigest':gpu_image['digest']} (root/'agent-update-manifest.json').write_text( json.dumps(payload,sort_keys=True,separators=(',',':'))+'\n') PY diff --git a/scripts/ci/push-images.sh b/scripts/ci/push-images.sh index 4039af8..a2a121c 100644 --- a/scripts/ci/push-images.sh +++ b/scripts/ci/push-images.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -mode=${1:?Expected server, agent or latest} -case "$mode" in server|agent|latest) ;; *) echo 'Usage: push-images.sh server|agent|latest' >&2; exit 2 ;; esac +mode=${1:?Expected server, agent, agent-gpu or latest} +case "$mode" in server|agent|agent-gpu|latest) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu|latest' >&2; exit 2 ;; esac sha=$(git rev-parse HEAD) if [[ "$mode" == latest ]]; then components=(server agent); else components=("$mode"); fi export DOCKER_CONFIG @@ -11,6 +11,7 @@ repository() { case "$1" in server) printf 'eltruncho/heimdall' ;; agent) printf 'eltruncho/heimdall-agent' ;; + agent-gpu) printf 'eltruncho/heimdall-agent-gpu' ;; esac } : "${DOCKERHUB_USERNAME:?Docker Hub user is required}" diff --git a/scripts/ci/security.sh b/scripts/ci/security.sh index 47a71d2..cd42440 100644 --- a/scripts/ci/security.sh +++ b/scripts/ci/security.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail mode=${1:-all} -case "$mode" in dependencies|server|agent|all) ;; *) echo 'Usage: security.sh [dependencies|server|agent|all]' >&2; exit 2 ;; esac +case "$mode" in dependencies|server|agent|agent-gpu|all) ;; *) echo 'Usage: security.sh [dependencies|server|agent|agent-gpu|all]' >&2; exit 2 ;; esac skip_restore=false if [[ $# -gt 1 ]]; then if [[ "$mode" == dependencies && $# == 2 && "${2}" == --no-restore ]]; then @@ -71,7 +71,7 @@ scan_image() ( exit 1 ) case "$mode" in - all) components=(server agent) ;; + all) components=(server agent agent-gpu) ;; *) components=("$mode") ;; esac for component in "${components[@]}"; do diff --git a/scripts/ci/test_ci.py b/scripts/ci/test_ci.py index 9ee3359..4767b7f 100644 --- a/scripts/ci/test_ci.py +++ b/scripts/ci/test_ci.py @@ -83,6 +83,23 @@ class TestPlanTests(unittest.TestCase): self.assertEqual(len(planner.plan(['global.json'])['suites']), len(planner.TESTS)) self.assertEqual(planner.plan(['docs/README.md'])['suites'], []) +class GpuAgentImageTests(unittest.TestCase): + def test_cpu_default_stays_independent_of_nvidia_runtime(self): + dockerfile = (REPO_ROOT/'docker/Dockerfile.agent').read_text() + compose = (REPO_ROOT/'docker/docker-compose.agent.dev.yml').read_text() + self.assertNotIn('nvidia/cuda', dockerfile) + self.assertNotIn('Agent__InferenceExecutionProvider: CUDA', compose) + self.assertNotIn('driver: nvidia', compose) + + def test_gpu_runtime_and_optional_overlay_pin_cuda_runtime_and_provider(self): + dockerfile = (REPO_ROOT/'docker/Dockerfile.agent.gpu').read_text() + compose = (REPO_ROOT/'docker/docker-compose.agent.dev.gpu-nvidia.yml').read_text() + self.assertIn('nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9', dockerfile) + self.assertIn('Microsoft.ML.OnnxRuntime.Gpu', (REPO_ROOT/'src/Heimdall.Agent/Heimdall.Agent.csproj').read_text()) + self.assertIn('Agent__InferenceExecutionProvider: CUDA', compose) + self.assertIn('driver: nvidia', compose) + self.assertIn('capabilities: [gpu]', compose) + class AdvisoryTests(unittest.TestCase): def check(self, data): with tempfile.TemporaryDirectory() as temp: @@ -150,5 +167,14 @@ class ReleaseTests(unittest.TestCase): with self.assertRaisesRegex(SystemExit, 'already public'): self.execute(public=True) +class OfflineReleaseAcceptanceTests(unittest.TestCase): + def test_publish_signs_and_uploads_cpu_and_gpu_image_manifests(self): + result = subprocess.run( + [sys.executable, str(ROOT/'accept-release-offline.py')], + cwd=REPO_ROOT, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn('CPU/GPU image digests', result.stdout) + self.assertIn('six simulated pushes', result.stdout) + if __name__ == '__main__': unittest.main() diff --git a/scripts/ci/validate-compose.sh b/scripts/ci/validate-compose.sh index ebca543..9cee2f1 100755 --- a/scripts/ci/validate-compose.sh +++ b/scripts/ci/validate-compose.sh @@ -21,6 +21,10 @@ for gpu in nvidia amd intel; do --profile "gpu-$gpu-inventory" done +compose -f docker/docker-compose.agent.dev.yml \ + -f docker/docker-compose.agent.dev.gpu-nvidia.yml \ + --profile gpu-nvidia + for required in DATABASE_URL POSTGRES_PASSWORD JWT__KEY JWT__REFRESHKEY; do if env "$required=" docker compose --env-file .env.example \ -f docker/docker-compose.yml config --quiet >/dev/null 2>&1; then diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index 471f650..a7990b8 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -9,7 +9,7 @@ Use this skill when changing ONNX Runtime packages, execution provider configura ## Project-specific workflow -- The default Agent build and published `docker/Dockerfile.agent` remain CPU-only. Do not add NVIDIA runtime/device requirements to the default Agent Compose files. +- The default Agent build and published `docker/Dockerfile.agent` remain CPU-only. Do not add NVIDIA runtime/device requirements to the default Agent Compose files. CUDA support is opt-in through `docker/Dockerfile.agent.gpu`, `docker/docker-compose.agent.dev.gpu-nvidia.yml`, and a separately signed release image manifest. - Configure provider choice through `Agent:InferenceExecutionProvider` (environment variable `Agent__InferenceExecutionProvider`). `CPU` is the default. `CUDA` is optional and valid only in a runtime containing the official ONNX Runtime GPU package plus compatible CUDA/cuDNN native libraries and host driver access. - Keep the CPU and GPU NuGet dependency graphs in their separate lock files. Restore each variant explicitly and in locked mode after changing dependencies: @@ -23,6 +23,8 @@ Use this skill when changing ONNX Runtime packages, execution provider configura - Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output. - Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution. +- The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; refresh it only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest. + ## Current limitation -The codebase contains CPU Agent image publication only. Selecting CUDA in that image must fall back to CPU; do not describe inventory overlays as GPU inference. A GPU image/runtime, publication and installer/UI selection, and hardware acceptance need separate implementation and evidence. +The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. Their image/Compose build acceptance and physical CUDA execution remain open until those runs succeed. diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj index a6de5c9..ca4d619 100644 --- a/src/Heimdall.Agent/Heimdall.Agent.csproj +++ b/src/Heimdall.Agent/Heimdall.Agent.csproj @@ -12,6 +12,7 @@ packages.gpu.lock.json + linux-x64 packages.lock.json diff --git a/src/Heimdall.Agent/Services/DockerUpdateService.cs b/src/Heimdall.Agent/Services/DockerUpdateService.cs index 8f5428a..d2a4e91 100644 --- a/src/Heimdall.Agent/Services/DockerUpdateService.cs +++ b/src/Heimdall.Agent/Services/DockerUpdateService.cs @@ -53,26 +53,37 @@ public sealed class DockerUpdateService : BackgroundService _options.UpdatePublicKeyPath, _options.UpdatePublicKeyPem); if (!string.Equals(signed.Version, release.Version, StringComparison.Ordinal) || !string.Equals(signed.ContainerImage, release.ContainerImage, StringComparison.Ordinal) || - !string.Equals(signed.ContainerImageDigest, release.ContainerImageDigest, StringComparison.OrdinalIgnoreCase)) + !string.Equals(signed.ContainerImageDigest, release.ContainerImageDigest, StringComparison.OrdinalIgnoreCase) || + !string.Equals(signed.ContainerImageGpu, release.ContainerImageGpu, StringComparison.Ordinal) || + !string.Equals(signed.ContainerImageGpuDigest, release.ContainerImageGpuDigest, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Docker image differs from the signed release manifest"); var latest = release.Version; var current = _options.Version; if (!IsNewerVersion(current, latest)) { _logger.LogInformation("Up to date ({V})", current); return; } _logger.LogInformation("Update available: {C} -> {A}", current, latest); - if (!IsSha256Digest(release.ContainerImageDigest)) + var useCudaImage = string.Equals(_options.InferenceExecutionProvider, "CUDA", StringComparison.OrdinalIgnoreCase); + if (useCudaImage && (string.IsNullOrWhiteSpace(release.ContainerImageGpu) || + !IsSha256Digest(release.ContainerImageGpuDigest))) + { + _logger.LogWarning("Release does not provide a signed CUDA Agent image; leaving the current GPU Agent unchanged"); + return; + } + var selectedDigest = useCudaImage ? release.ContainerImageGpuDigest : release.ContainerImageDigest; + var selectedImage = useCudaImage ? release.ContainerImageGpu : release.ContainerImage; + if (!IsSha256Digest(selectedDigest)) { _logger.LogError("Update manifest has no valid immutable agent image digest; refusing tag-based update"); return; } var cid = info.ContainerId; if (string.IsNullOrEmpty(cid)) return; - var image = release.ContainerImage; + var image = selectedImage; if (image is null || !IsValidImageRepository(image)) { _logger.LogError("Update manifest has no valid agent image repository; refusing update"); return; } - var full = image + "@" + release.ContainerImageDigest; + var full = image + "@" + selectedDigest; _logger.LogInformation("Pulling {Image}...", full); var (pe, po) = await RunDocker(["pull", full], ct); if (pe != 0) { _logger.LogError("docker pull failed: {O}", po); return; } @@ -254,6 +265,8 @@ public sealed class DockerUpdateService : BackgroundService [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; init; } [JsonPropertyName("containerImage")] public string? ContainerImage { get; init; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; } + [JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; init; } + [JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; init; } [JsonPropertyName("signedManifest")] public string? SignedManifest { get; init; } [JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; init; } } diff --git a/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs b/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs index 04d1cf7..b328c7a 100644 --- a/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs +++ b/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs @@ -45,7 +45,11 @@ internal static class ReleaseSignatureVerifier release.Assets.Any(x => string.IsNullOrWhiteSpace(x.Key) || !IsSha256(x.Value)) || string.IsNullOrWhiteSpace(release.ContainerImage) || release.ContainerImage.Contains('@') || - !IsImageDigest(release.ContainerImageDigest)) + !IsImageDigest(release.ContainerImageDigest) || + ((release.ContainerImageGpu is null) != (release.ContainerImageGpuDigest is null)) || + (release.ContainerImageGpu is not null && + (string.IsNullOrWhiteSpace(release.ContainerImageGpu) || release.ContainerImageGpu.Contains('@') || + !IsImageDigest(release.ContainerImageGpuDigest)))) throw new InvalidOperationException("Signed release manifest is incomplete"); return release; } @@ -62,4 +66,6 @@ internal sealed class SignedAgentRelease [JsonPropertyName("assets")] public Dictionary Assets { get; init; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; init; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; } + [JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; init; } + [JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; init; } } diff --git a/src/Heimdall.Agent/packages.gpu.lock.json b/src/Heimdall.Agent/packages.gpu.lock.json index 1b7924e..3462760 100644 --- a/src/Heimdall.Agent/packages.gpu.lock.json +++ b/src/Heimdall.Agent/packages.gpu.lock.json @@ -352,6 +352,43 @@ "heimdall.mdns": { "type": "Project" } + }, + "net10.0/linux-x64": { + "Magick.NET-Q16-AnyCPU": { + "type": "Direct", + "requested": "[14.16.0, )", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Linux": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "1llC85TrCC69e18WSBF5rAHnbvwLY9wI+wX8PUpMfQhtSehZlJImMfXoCEdPYTtvLR/5ad/wHG43LwRLSxqp+g==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Windows": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "vscA3rOmdgyOXeXWMheBC4okYGvoHEK3bOC/RudikJyR3wY4mbiukfUqa94etShJ+YQYA9q35DOz0bxrAOUOKw==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "SQLite": { + "type": "Transitive", + "resolved": "3.53.4", + "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" + }, + "System.ServiceProcess.ServiceController": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ==" + } } } } \ No newline at end of file diff --git a/src/Heimdall.Web/Components/SiteInstallPanel.razor b/src/Heimdall.Web/Components/SiteInstallPanel.razor index c112e39..71300a7 100644 --- a/src/Heimdall.Web/Components/SiteInstallPanel.razor +++ b/src/Heimdall.Web/Components/SiteInstallPanel.razor @@ -35,6 +35,18 @@ } +@if ((_method == "docker-compose" || _method == "docker-run") && CanGenerateDocker && + !string.IsNullOrWhiteSpace(_agentGpuImageReference)) +{ + + @Text["SiteInstallPanel_NvidiaInference"] + + @if (_useGpuImage) + { + @Text["SiteInstallPanel_NvidiaRequirement"] + } +} + @if (_method == "docker-compose" && CanGenerateDocker) { @Text["SiteInstallPanel_Configuration"] @@ -94,7 +106,9 @@ else if (_method == "windows-service") private string _operatingSystem = "linux"; private string _method = "linux-systemd"; private string? _agentImageReference; + private string? _agentGpuImageReference; private string? _updatePublicKeyPem; + private bool _useGpuImage; private bool CanGenerateDocker => !string.IsNullOrWhiteSpace(_agentImageReference) && !string.IsNullOrWhiteSpace(_updatePublicKeyPem); @@ -165,6 +179,9 @@ else if (_method == "windows-service") if (!string.IsNullOrWhiteSpace(release?.ContainerImage) && !string.IsNullOrWhiteSpace(release.ContainerImageDigest)) _agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}"; + if (!string.IsNullOrWhiteSpace(release?.ContainerImageGpu) && + !string.IsNullOrWhiteSpace(release.ContainerImageGpuDigest)) + _agentGpuImageReference = $"{release.ContainerImageGpu}@{release.ContainerImageGpuDigest}"; _updatePublicKeyPem = release?.UpdatePublicKeyPem; } catch @@ -179,10 +196,15 @@ else if (_method == "windows-service") { var safeName = Slugify(SiteName); var pem = EscapeYamlString(_updatePublicKeyPem ?? ""); + var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; + var provider = _useGpuImage ? "CUDA" : "CPU"; + var gpuReservation = _useGpuImage + ? "deploy:\n resources:\n reservations:\n devices:\n - driver: nvidia\n count: all\n capabilities: [gpu]\n" + : string.Empty; return $$""" services: heimdall-agent: - image: {{_agentImageReference}} + image: {{image}} container_name: heimdall-agent-{{safeName}} restart: unless-stopped user: "1654:1654" @@ -193,6 +215,7 @@ else if (_method == "windows-service") Agent__AgentName: {{YamlScalar(SiteName)}} Agent__HeartbeatIntervalSeconds: "30" Agent__StateDirectory: /var/lib/heimdall + Agent__InferenceExecutionProvider: {{provider}} Agent__UpdatePublicKeyPem: "{{pem}}" volumes: - agent_state_{{safeName}}:/var/lib/heimdall @@ -205,9 +228,10 @@ else if (_method == "windows-service") timeout: 5s retries: 3 start_period: 15s + __NVIDIA_RESERVATION__ agent-state-init: - image: {{_agentImageReference}} + image: {{image}} user: "0:0" entrypoint: ["chown", "-R", "1654:1654", "/state"] volumes: @@ -216,7 +240,7 @@ else if (_method == "windows-service") volumes: agent_state_{{safeName}}: - """; + """.Replace("__NVIDIA_RESERVATION__", gpuReservation, StringComparison.Ordinal); } } @@ -236,11 +260,14 @@ else if (_method == "windows-service") { var name = "heimdall-agent-" + Slugify(SiteName); var volume = "heimdall-agent-state-" + Slugify(SiteName); + var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference; return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " + + (_useGpuImage ? "--gpus all " : "") + $"-e Agent__CentralUrl={ShellQuote(CentralUrl)} -e Agent__SiteToken={ShellQuote(SiteToken)} " + $"-e Agent__AgentName={ShellQuote(SiteName)} -e Agent__StateDirectory=/var/lib/heimdall " + + $"-e Agent__InferenceExecutionProvider={(_useGpuImage ? "CUDA" : "CPU")} " + $"-e Agent__UpdatePublicKeyPem={ShellQuote(_updatePublicKeyPem ?? "")} " + - $"-v {volume}:/var/lib/heimdall {_agentImageReference}"; + $"-v {volume}:/var/lib/heimdall {image}"; } } diff --git a/src/Heimdall.Web/Controllers/UpdatesController.cs b/src/Heimdall.Web/Controllers/UpdatesController.cs index f4d07d6..7e1c8c4 100644 --- a/src/Heimdall.Web/Controllers/UpdatesController.cs +++ b/src/Heimdall.Web/Controllers/UpdatesController.cs @@ -146,9 +146,12 @@ public class UpdatesController : ControllerBase catch (CryptographicException) { } catch (ArgumentException) { } } - var image = await FetchAgentImageManifestAsync(release.Assets, client, ct); + var image = await FetchAgentImageManifestAsync(release.Assets, "agent-image.json", client, ct); result.ContainerImage = image?.Image; result.ContainerImageDigest = image?.Digest; + var gpuImage = await FetchAgentImageManifestAsync(release.Assets, "agent-image-gpu.json", client, ct); + result.ContainerImageGpu = gpuImage?.Image; + result.ContainerImageGpuDigest = gpuImage?.Digest; var manifestBytes = await FetchBoundedReleaseAssetAsync(release.Assets, "agent-update-manifest.json", client, 1_048_576, ct); var signatureBytes = await FetchBoundedReleaseAssetAsync(release.Assets, @@ -164,9 +167,10 @@ public class UpdatesController : ControllerBase catch (Exception ex) { _logger.LogError(ex, "Failed to fetch release"); return null; } } - private static async Task FetchAgentImageManifestAsync(List? assets, HttpClient client, CancellationToken ct) + private static async Task FetchAgentImageManifestAsync(List? assets, + string assetName, HttpClient client, CancellationToken ct) { - var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, "agent-image.json", StringComparison.OrdinalIgnoreCase)); + var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, assetName, StringComparison.OrdinalIgnoreCase)); var expectedSha256 = asset is null ? null : ExtractSha256(asset.Digest); if (asset is null || !IsSha256Digest(expectedSha256)) return null; try @@ -284,6 +288,8 @@ public class UpdatesController : ControllerBase [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } + [JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; set; } + [JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; set; } [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; set; } [JsonPropertyName("signedManifest")] public string? SignedManifest { get; set; } [JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; set; } diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index bcd7fc9..2c32313 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -4065,6 +4065,12 @@ Docker Run + + Use NVIDIA GPU inference + + + Requires an NVIDIA GPU, NVIDIA Container Toolkit, and a compatible host driver. Inference falls back to CPU if CUDA cannot be initialized. + Set up your administrator account Create the first account. This one-time setup closes after the administrator is created. Name diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 4dcbbdf..10ae671 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -4065,6 +4065,12 @@ Docker Run + + Utiliser l’inférence GPU NVIDIA + + + Nécessite un GPU NVIDIA, le NVIDIA Container Toolkit et un pilote hôte compatible. L’inférence repasse sur le CPU si CUDA ne peut pas démarrer. + Configurer le compte administrateur Créez le premier compte. Cet assistant ne sera plus accessible après sa création. Nom diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index c47dcd8..738dfe1 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -4065,6 +4065,12 @@ Docker Run + + Use NVIDIA GPU inference + + + Requires an NVIDIA GPU, NVIDIA Container Toolkit, and a compatible host driver. Inference falls back to CPU if CUDA cannot be initialized. + Set up your administrator account Create the first account. This one-time setup closes after the administrator is created. Name diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index ed5e844..233b85d 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -1445,7 +1445,7 @@ public record CreateApiKeyResult( [property: JsonPropertyName("siteId")] Guid? SiteId, [property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt); -public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; set; } } +public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } [JsonPropertyName("containerImageGpu")] public string? ContainerImageGpu { get; set; } [JsonPropertyName("containerImageGpuDigest")] public string? ContainerImageGpuDigest { get; set; } [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; set; } } public class PlatformAssetInfo { [JsonPropertyName("url")] public string Url { get; set; } = ""; [JsonPropertyName("sha256")] public string? Sha256 { get; set; } [JsonPropertyName("size")] public long Size { get; set; } } public record SiteCascadeInfo([property: JsonPropertyName("agentCount")] int AgentCount, [property: JsonPropertyName("cameraCount")] int CameraCount); diff --git a/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj b/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj index 3f4c743..1e385e4 100644 --- a/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj +++ b/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj @@ -9,6 +9,7 @@ packages.gpu.lock.json + linux-x64 packages.lock.json diff --git a/tests/Heimdall.Agent.Tests/Services/ReleaseSignatureVerifierTests.cs b/tests/Heimdall.Agent.Tests/Services/ReleaseSignatureVerifierTests.cs new file mode 100644 index 0000000..e4df07f --- /dev/null +++ b/tests/Heimdall.Agent.Tests/Services/ReleaseSignatureVerifierTests.cs @@ -0,0 +1,42 @@ +using System.Security.Cryptography; +using System.Text; +using Heimdall.Agent.Services; + +namespace Heimdall.Agent.Tests.Services; + +public sealed class ReleaseSignatureVerifierTests +{ + [Fact] + public void Verify_UsesSignedCpuAndGpuImageReferences() + { + using var signer = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var (manifest, signature) = Sign(signer, """ + {"version":"1.2.3","assets":{"linux-x64":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"containerImage":"registry.test/agent","containerImageDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","containerImageGpu":"registry.test/agent-gpu","containerImageGpuDigest":"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"} + """); + + var release = ReleaseSignatureVerifier.Verify(manifest, signature, null, signer.ExportSubjectPublicKeyInfoPem()); + + release.ContainerImage.ShouldBe("registry.test/agent"); + release.ContainerImageGpu.ShouldBe("registry.test/agent-gpu"); + release.ContainerImageGpuDigest.ShouldBe("sha256:" + new string('b', 64)); + } + + [Fact] + public void Verify_RejectsIncompleteGpuImageReferencePair() + { + using var signer = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var (manifest, signature) = Sign(signer, """ + {"version":"1.2.3","assets":{"linux-x64":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"containerImage":"registry.test/agent","containerImageDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","containerImageGpu":"registry.test/agent-gpu"} + """); + + Should.Throw(() => + ReleaseSignatureVerifier.Verify(manifest, signature, null, signer.ExportSubjectPublicKeyInfoPem())); + } + + private static (string Manifest, string Signature) Sign(ECDsa signer, string json) + { + var bytes = Encoding.UTF8.GetBytes(json.Trim()); + var signature = signer.SignData(bytes, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence); + return (Convert.ToBase64String(bytes), Convert.ToBase64String(signature)); + } +} diff --git a/tests/Heimdall.Agent.Tests/packages.gpu.lock.json b/tests/Heimdall.Agent.Tests/packages.gpu.lock.json index d8db8a4..40c0397 100644 --- a/tests/Heimdall.Agent.Tests/packages.gpu.lock.json +++ b/tests/Heimdall.Agent.Tests/packages.gpu.lock.json @@ -948,6 +948,63 @@ "Microsoft.Extensions.Logging.Abstractions": "[10.0.13, )" } } + }, + "net10.0/linux-x64": { + "Magick.NET-Q16-AnyCPU": { + "type": "Transitive", + "resolved": "14.16.0", + "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==", + "dependencies": { + "Magick.NET.Core": "14.16.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Linux": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "1llC85TrCC69e18WSBF5rAHnbvwLY9wI+wX8PUpMfQhtSehZlJImMfXoCEdPYTtvLR/5ad/wHG43LwRLSxqp+g==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "Microsoft.ML.OnnxRuntime.Gpu.Windows": { + "type": "Transitive", + "resolved": "1.22.0", + "contentHash": "vscA3rOmdgyOXeXWMheBC4okYGvoHEK3bOC/RudikJyR3wY4mbiukfUqa94etShJ+YQYA9q35DOz0bxrAOUOKw==", + "dependencies": { + "Microsoft.ML.OnnxRuntime.Managed": "1.22.0" + } + }, + "SQLite": { + "type": "Transitive", + "resolved": "3.53.4", + "contentHash": "KN7jeWqgUPeBRe1FlcpZURzxomuKKEKHmBBQfg+Nx7NkY1LjKhzHvH+3ASkNvhayESE34nMBinL9CV21JfPRJw==" + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "DkNjtQyPR5Ud/zHnWHdsOuKbFRL9nIC92Q76z0NmHVDoQm40toLtsGFTIWq7toBoVa6fo/DInL3PLxY3Asixyw==" + }, + "System.Management": { + "type": "Transitive", + "resolved": "6.0.1", + "contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==", + "dependencies": { + "System.CodeDom": "6.0.0" + } + }, + "System.Security.Cryptography.Pkcs": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "a+EovgC1fBnwdlQ6cn3j4JFBfKqiFaFvoAhjisOoSvazLAcIznaBzPQP0oYnvccmeXfqUH1KebVZOxSeH6rMaw==" + }, + "System.ServiceProcess.ServiceController": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ==", + "dependencies": { + "System.Diagnostics.EventLog": "10.0.13" + } + } } } } \ No newline at end of file diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs index ebb54f3..9b86bfc 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs @@ -5,6 +5,7 @@ using Heimdall.Web.Services; using Microsoft.Extensions.DependencyInjection; using MudBlazor; using Shouldly; +using YamlDotNet.RepresentationModel; namespace Heimdall.Web.Tests.Components.Pages; @@ -67,8 +68,61 @@ public class SiteDetailTests : PageTestBase compose.ShouldContain("network_mode: host"); compose.ShouldContain("Agent__CentralUrl: \"http://localhost\""); compose.ShouldContain("Agent__SiteToken: \"tok-detail-42\""); + compose.ShouldContain("Agent__InferenceExecutionProvider: CPU"); + compose.ShouldNotContain("driver: nvidia"); + compose.ShouldNotContain("--gpus"); compose.ShouldNotContain("postgresql"); compose.ShouldNotContain("ollama"); + var agent = GetAgentService(ParseCompose(compose)); + agent.Children.ShouldNotContainKey(new YamlScalarNode("deploy")); + var environment = (YamlMappingNode)agent.Children[new YamlScalarNode("environment")]; + ((YamlScalarNode)environment.Children[new YamlScalarNode("Agent__InferenceExecutionProvider")]).Value.ShouldBe("CPU"); + }); + } + + [Fact] + public void SiteDetail_ChoisirImageNvidia_GenereComposeAvecGpuEtProviderCuda() + { + Handler.OnGet("api/updates/latest", AgentReleaseWithGpu()); + Handler.OnGet("api/sites/", new SiteItem( + SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10))); + Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-gpu", DateTime.UtcNow.AddHours(24))); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, SiteId)); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Générer un token")); + cut.FindAll("button").Single(b => b.TextContent.Contains("Générer un token")).Click(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("tok-detail-gpu")); + cut.FindAll("button").Single(b => b.TextContent.Contains("Docker", StringComparison.OrdinalIgnoreCase)).Click(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Utiliser l’inférence GPU NVIDIA")); + + cut.Find("input[type=checkbox]").Change(true); + cut.WaitForAssertion(() => + { + var compose = cut.Find("pre code").TextContent; + compose.ShouldContain("image: registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64)); + compose.ShouldContain("Agent__InferenceExecutionProvider: CUDA"); + compose.ShouldContain("driver: nvidia"); + compose.ShouldContain("capabilities: [gpu]"); + compose.ShouldContain("\n deploy:\n resources:\n reservations:"); + var agent = GetAgentService(ParseCompose(compose)); + ((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value.ShouldBe( + "registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64)); + var deploy = (YamlMappingNode)agent.Children[new YamlScalarNode("deploy")]; + var resources = (YamlMappingNode)deploy.Children[new YamlScalarNode("resources")]; + var reservations = (YamlMappingNode)resources.Children[new YamlScalarNode("reservations")]; + var devices = (YamlSequenceNode)reservations.Children[new YamlScalarNode("devices")]; + ((YamlScalarNode)((YamlMappingNode)devices.Children[0]).Children[new YamlScalarNode("driver")]).Value.ShouldBe("nvidia"); + }); + + cut.FindAll("button").Single(b => b.TextContent.Contains("Docker Run", StringComparison.OrdinalIgnoreCase)).Click(); + cut.WaitForAssertion(() => + { + var commands = cut.FindAll("pre code").Select(code => code.TextContent).ToArray(); + var run = commands[1]; + run.ShouldContain("--gpus all"); + run.ShouldContain("Agent__InferenceExecutionProvider=CUDA"); + run.ShouldContain("registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64)); }); } @@ -137,6 +191,29 @@ public class SiteDetailTests : PageTestBase UpdatePublicKeyPem = "test-public-key" }; + private static LatestReleaseInfo AgentReleaseWithGpu() => new() + { + Version = "1.0.0", + ContainerImage = "registry.example/heimdall-agent", + ContainerImageDigest = "sha256:" + new string('a', 64), + ContainerImageGpu = "registry.example/heimdall-agent-gpu", + ContainerImageGpuDigest = "sha256:" + new string('b', 64), + UpdatePublicKeyPem = "test-public-key" + }; + + private static YamlMappingNode ParseCompose(string compose) + { + var stream = new YamlStream(); + stream.Load(new StringReader(compose)); + return (YamlMappingNode)stream.Documents[0].RootNode; + } + + private static YamlMappingNode GetAgentService(YamlMappingNode root) + { + var services = (YamlMappingNode)root.Children[new YamlScalarNode("services")]; + return (YamlMappingNode)services.Children[new YamlScalarNode("heimdall-agent")]; + } + [Fact] public void SiteDetail_AucunIdentifiant_AfficheMessage() { diff --git a/tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj b/tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj index 6856036..103eee5 100644 --- a/tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj +++ b/tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj @@ -18,6 +18,7 @@ + diff --git a/tests/Heimdall.Web.Tests/packages.lock.json b/tests/Heimdall.Web.Tests/packages.lock.json index b773825..f62cf2c 100644 --- a/tests/Heimdall.Web.Tests/packages.lock.json +++ b/tests/Heimdall.Web.Tests/packages.lock.json @@ -106,6 +106,12 @@ "resolved": "3.1.4", "contentHash": "5mj99LvCqrq3CNi06xYdyIAXOEh+5b33F2nErCzI5zWiDdLHXiPXEWFSUAF8zlIv0ZWqjZNCwHTQeAPYbF3pCg==" }, + "YamlDotNet": { + "type": "Direct", + "requested": "[18.1.0, )", + "resolved": "18.1.0", + "contentHash": "5K+9KFg2TdTl7VXv88Qzi/0lqK6JFoNP3lRuImPYGRV7K/QYklDyTrj4+A+KAki1JsQi6qKY+hDyY7d6WRqjrw==" + }, "AngleSharp.Css": { "type": "Transitive", "resolved": "1.0.1", @@ -1187,7 +1193,6 @@ "FluentValidation.DependencyInjectionExtensions": "[11.11.0, )", "Heimdall.Domain": "[1.0.0, )", "MediatR": "[12.5.0, )", - "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )", "Microsoft.Data.Sqlite": "[10.0.13, )", "Microsoft.EntityFrameworkCore": "[10.0.13, )", "Microsoft.EntityFrameworkCore.Sqlite": "[10.0.13, )", @@ -1200,8 +1205,7 @@ "heimdall.domain": { "type": "Project", "dependencies": { - "Heimdall.Domain.Primitives": "[1.0.0, )", - "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )" + "Heimdall.Domain.Primitives": "[1.0.0, )" } }, "heimdall.domain.primitives": { diff --git a/todo.md b/todo.md index 1da5a00..6680c6e 100644 --- a/todo.md +++ b/todo.md @@ -48,7 +48,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. Un vertical initial ajoute le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read Data Protection à durée limitée, la revalidation des droits caméra et un lecteur WHEP dans le détail caméra ; audio/PTZ restent exclus. Les builds/tests ciblés API/Web (7 tests) et Agent (1 test), la syntaxe JS et `git diff --check` passent. La recette Compose jetable a validé bootstrap admin/site, enregistrement Agent, caméra RTSP synthétique assignée/activée, demande publish-session et démarrage du relais, ticket read autorisé + callback MediaMTX 200, rejet ticket forgé 401 et rejet caméra inconnue. Une requête WHEP avec SDP invalide a atteint MediaMTX et retourné 400; aucun navigateur/frame décodée ni arrêt par désactivation API n’a été vérifié. Compose `hmd-webrtc-e9e542` a été arrêté avec `down --volumes --remove-orphans`, puis ses conteneurs, volumes et réseaux vérifiés absents; les secrets/cache acceptance ont été supprimés. Validation caméra physique, LAN, TURN externe, lecture d’une vraie offre SDP et cycle désactivation restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt. Test d'inférence ONNX CPU 1080p autonome : 1/1. Restent image/runtime GPU, sélection UI/installateur, manifeste de release, test complet et matériel CUDA réel. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d'inventaire restent distincts. L’Agent possède un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d'image GPU intégré au manifeste ECDSA de release, un choix CPU/CUDA dans l’installateur Docker et la conservation de ce variant pendant les mises à jour. CPU reste le défaut. Validation locale : restores CPU/GPU verrouillés; builds Agent CPU/GPU; 4 tests de sélection/fallback, 2 tests de signature image CPU/GPU et inférence réelle CPU du modèle avec le package GPU; 10 tests Web `SiteDetailTests` couvrent Compose CPU sans device et Compose/Docker Run CUDA avec digest. L'acceptation offline de release signée a passé : manifeste CPU/GPU, digests, 10 assets, sommes et signature ECDSA, six pushes simulés, sans contacter Docker ni Gitea/Hub réels. Les tests de configuration Compose et scripts vérifient le runtime sans GPU. Restent le build + recette Compose jetable après créneau Docker et l'exécution sur matériel NVIDIA réel; aucun GPU réel n'est déclaré validé. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** L'édition des groupes permet maintenant de lister les caméras des sites, d'accorder/révoquer les accès de groupe et d'afficher les noms de site/caméra via l'API existante. Restent la validation produit et la vérification de l'union accès direct/groupe ainsi que des priorités dans l'interface. -- 2.54.1 From 06aa5ea31a48840a25ef3b8b91ea8496afa69d7b Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 22:46:33 +0100 Subject: [PATCH 14/40] test(ci): verify signed CUDA release image offline --- scripts/ci/accept-release-offline.py | 4 ++++ scripts/ci/publish.sh | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/scripts/ci/accept-release-offline.py b/scripts/ci/accept-release-offline.py index 1234820..ef81fdd 100755 --- a/scripts/ci/accept-release-offline.py +++ b/scripts/ci/accept-release-offline.py @@ -31,6 +31,10 @@ def run(command, *, cwd, env, label): result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True) if result.returncode: output = (result.stdout + result.stderr).replace(DOCKER_TOKEN, '[redacted]').replace(RELEASE_TOKEN, '[redacted]') + if label == 'publish.sh': + provenance_path = cwd / 'artifacts/packages/provenance.json' + if provenance_path.exists(): + output += '\nOffline provenance: ' + json.dumps(json.loads(provenance_path.read_text()), sort_keys=True) raise RuntimeError(f'{label} failed ({result.returncode}):\n{output[-12000:]}') return result.stdout diff --git a/scripts/ci/publish.sh b/scripts/ci/publish.sh index fec2a17..639a93a 100644 --- a/scripts/ci/publish.sh +++ b/scripts/ci/publish.sh @@ -44,7 +44,9 @@ PY (cd artifacts/packages && sha256sum --check SHA256SUMS) printf '%s' "${tag#v}" > artifacts/version bash scripts/ci/images.sh -bash scripts/ci/security.sh agent-gpu +for image_component in server agent agent-gpu; do + bash scripts/ci/security.sh "$image_component" +done # No mutation is attempted until all credentials, provenance and local builds pass. export DOCKER_CONFIG DOCKER_CONFIG=$(mktemp -d) -- 2.54.1 From ae3203222b1e1aec188821c7ab25e2158a2a2f24 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 00:01:17 +0100 Subject: [PATCH 15/40] fix: harden GPU fallback and group access UI --- docker/Dockerfile.agent | 2 +- docker/Dockerfile.agent.gpu | 4 +- .../docker-compose.agent.dev.gpu-nvidia.yml | 1 + docs/gpu-runtime.md | 2 +- skills/gpu-inference/SKILL.md | 4 +- skills/group-access/SKILL.md | 34 ++++++ skills/server-healthchecks/SKILL.md | 6 +- src/Heimdall.Agent/Program.cs | 4 +- .../Services/FrameAnalyzerService.cs | 20 ++-- .../OnnxExecutionProviderSelection.cs | 9 +- .../Components/Pages/Admin/GroupsPage.razor | 100 +++++++++++++----- .../Localization/SharedResources.en.resx | 12 +++ .../Localization/SharedResources.fr.resx | 12 +++ .../Localization/SharedResources.resx | 12 +++ .../Services/HeimdallApiClient.cs | 12 ++- .../OnnxExecutionProviderSelectionTests.cs | 21 ++++ .../Scenarios/CameraAuthorizationScenarios.cs | 62 +++++++++++ .../Components/Pages/GroupsPageTests.cs | 40 ++++++- .../Services/HeimdallApiClientTests.cs | 22 +++- todo.md | 8 +- 20 files changed, 329 insertions(+), 58 deletions(-) create mode 100644 skills/group-access/SKILL.md diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent index ca19f13..c04d3d0 100644 --- a/docker/Dockerfile.agent +++ b/docker/Dockerfile.agent @@ -18,6 +18,6 @@ ENV ASPNETCORE_URLS=http://127.0.0.1:8080 COPY --from=build /out/ ./ COPY models/yolov8n.onnx ./models/yolov8n.onnx EXPOSE 8080 -HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q --spider http://127.0.0.1:8080/healthz || exit 1 +HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1 USER 1654:1654 ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"] diff --git a/docker/Dockerfile.agent.gpu b/docker/Dockerfile.agent.gpu index d186776..fac6582 100644 --- a/docker/Dockerfile.agent.gpu +++ b/docker/Dockerfile.agent.gpu @@ -11,7 +11,7 @@ RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-rest FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee AS dotnet-runtime -FROM --platform=linux/amd64 nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime +FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime WORKDIR /app ENV DOTNET_ROOT=/usr/share/dotnet \ PATH=/usr/share/dotnet:$PATH \ @@ -26,6 +26,6 @@ COPY --from=dotnet-runtime /usr/share/dotnet/ /usr/share/dotnet/ COPY --from=build /out/ ./ COPY models/yolov8n.onnx ./models/yolov8n.onnx EXPOSE 8080 -HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q --spider http://127.0.0.1:8080/healthz || exit 1 +HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1 USER 1654:1654 ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"] diff --git a/docker/docker-compose.agent.dev.gpu-nvidia.yml b/docker/docker-compose.agent.dev.gpu-nvidia.yml index 7b7a2cd..d02f6f7 100644 --- a/docker/docker-compose.agent.dev.gpu-nvidia.yml +++ b/docker/docker-compose.agent.dev.gpu-nvidia.yml @@ -1,6 +1,7 @@ # Optional development overlay. The default dev Compose remains CPU-only. services: heimdall-agent: + platform: linux/amd64 profiles: - gpu-nvidia image: heimdall-agent:gpu-local diff --git a/docs/gpu-runtime.md b/docs/gpu-runtime.md index 376c02d..5920ecf 100644 --- a/docs/gpu-runtime.md +++ b/docs/gpu-runtime.md @@ -23,7 +23,7 @@ The `docker-compose.gpu-{nvidia,amd,intel}.yml` files remain inventory-only overlays. For local development, the CPU default is `docker/docker-compose.agent.dev.yml`; use `docker/docker-compose.agent.dev.gpu-nvidia.yml` with `--profile gpu-nvidia` to -select the opt-in CUDA runtime. Intel and AMD inventory hosts may need +select the opt-in CUDA runtime, which fixes the Compose target to amd64 for its architecture-pinned NVIDIA base. Intel and AMD inventory hosts may need `VIDEO_GID` and `RENDER_GID` set to host group IDs that can access `/dev/dri`. The image and Compose build acceptance and physical CUDA execution have not diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index a7990b8..47ee6cd 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -18,12 +18,12 @@ Use this skill when changing ONNX Runtime packages, execution provider configura dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode ``` -- The Agent detects registered providers before creating a session. It reports the provider configured on the resulting session. If CUDA is requested but unavailable or session construction fails, log the reason without sensitive payloads and construct a CPU session. Keep provider selection isolated behind `OnnxExecutionProviderSelection` so the fallback can be tested without hardware. +- The Agent checks for detected NVIDIA hardware before enumerating ONNX providers or creating a session; some ONNX Runtime GPU builds can fault during native provider discovery when no driver device is attached, before managed fallback handling is possible. It reports the provider configured on the resulting session. If CUDA is requested but unavailable or session construction fails, log the reason without sensitive payloads and construct a CPU session. Keep provider selection isolated behind `OnnxExecutionProviderSelection` so the fallback can be tested without hardware. - Add tests for CPU-only selection, successful CUDA selection, missing CUDA provider, and CUDA session initialization failure. Also exercise the repository YOLO fixture with the CPU provider so package changes preserve real inference. - Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output. - Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution. -- The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; refresh it only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest. +- The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; the dev overlay targets `linux/amd64` and the Dockerfile uses that target rather than a constant `FROM --platform` override. Refresh the digest only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest. ## Current limitation diff --git a/skills/group-access/SKILL.md b/skills/group-access/SKILL.md new file mode 100644 index 0000000..f37d601 --- /dev/null +++ b/skills/group-access/SKILL.md @@ -0,0 +1,34 @@ +--- +name: group-access +description: Implement and accept Heimdall group membership and camera grants through the Admin UI and protected API. +--- + +# Group membership and camera access + +The Admin group editor is `src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor`. +Its API adapter is `HeimdallApiClient`; route templates must match +`GroupsController`. Member listing is `GET /api/groups/{groupId}/users`, add is +`POST /api/groups/{groupId}/users/{userId}`, and removal is +`DELETE /api/groups/{groupId}/users/{userId}`. Camera grants use the sibling +`/cameras` endpoints. Keep member selection name/email based in the UI; do not +ask administrators to copy opaque user IDs. + +Authorization is additive: effective camera access is the union of active +site-wide, direct, legacy, and live group grants, subject to role permissions +and deleted-resource checks. Removing one grant must preserve another valid +grant. Soft-deleted groups must stop granting access immediately. + +## Acceptance + +1. Run focused Web tests for `GroupsPageTests`, `HeimdallApiClientTests`, and + `ResourceAccessTests`. Assert API HTTP method/path, UI member identity and + camera/site labels, and add/remove behavior. +2. Build the source in a uniquely named disposable Compose project with + generated PostgreSQL/JWT credentials, loopback port, named volumes, and a + project-specific network. Bootstrap the first Admin through the setup API; + create a group, add a member using the production route, read the member + list, remove the member, and verify the empty list. Use only synthetic data. +3. Tear down that exact project with volumes and orphans, verify there are no + project containers, volumes, or networks, and delete generated secret files. +4. Update `todo.md` with the exact evidence and keep physical/deployment-only + claims separate from local acceptance. diff --git a/skills/server-healthchecks/SKILL.md b/skills/server-healthchecks/SKILL.md index 6e1cdff..fe1676e 100644 --- a/skills/server-healthchecks/SKILL.md +++ b/skills/server-healthchecks/SKILL.md @@ -7,7 +7,7 @@ description: Keep Heimdall container health probes aligned with the HTTP methods Use this workflow when changing `Dockerfile` health checks, Central Compose health checks, or Web health endpoint routing. -- The container probes `/healthz` on port 8080. ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy. +- Central and Agent containers probe `/healthz` on port 8080 (the development Agent may bind its host-mapped port). ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy. - In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD. -- Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required. -- For acceptance, build the Central image from the changed source in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm Compose reports healthy and remove only that project with `down --volumes --remove-orphans`. Verify no labeled containers, volumes, or networks remain. +- Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required. +- For acceptance, build the changed Central or Agent image from source in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy and remove only that project with `down --volumes --remove-orphans`. Verify no labeled containers, volumes, or networks remain. diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index b6c2d18..5185838 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -6,6 +6,7 @@ using Heimdall.Agent.Logging; using Heimdall.Agent.Services; using Heimdall.Application.Discovery; using Heimdall.Application.Metrics; +using Heimdall.Domain.Enums; using Heimdall.Mdns; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; @@ -151,7 +152,8 @@ builder.Services.AddSingleton(sp => new FrameAnalyzerServi sp.GetRequiredService(), sp.GetRequiredService(), inference: null, - inferenceExecutionProvider: sp.GetRequiredService>().Value.InferenceExecutionProvider)); + inferenceExecutionProvider: sp.GetRequiredService>().Value.InferenceExecutionProvider, + cudaDeviceAvailable: sp.GetRequiredService().GetInfo().GpuType == GpuAcceleration.NvidiaCuda)); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs index f512b32..66ab6c8 100644 --- a/src/Heimdall.Agent/Services/FrameAnalyzerService.cs +++ b/src/Heimdall.Agent/Services/FrameAnalyzerService.cs @@ -112,7 +112,7 @@ public sealed class FrameAnalyzerService : IDisposable internal FrameAnalyzerService(ILogger logger, CircuitBreaker? circuitBreaker, PipelineDegradationManager? degradationManager, Func? inference, - string? modelPath = null, string inferenceExecutionProvider = "CPU") + string? modelPath = null, string inferenceExecutionProvider = "CPU", bool cudaDeviceAvailable = true) { _testInference = inference; _logger = logger; @@ -125,7 +125,7 @@ public sealed class FrameAnalyzerService : IDisposable { try { - _session = CreateSession(_modelPath, inferenceExecutionProvider, out _executionProvider); + _session = CreateSession(_modelPath, inferenceExecutionProvider, cudaDeviceAvailable, out _executionProvider); _inputName = _session.InputMetadata.Keys.Single(); var input = _session.InputMetadata[_inputName]; var output = _session.OutputMetadata.Values.Single(); @@ -139,8 +139,8 @@ public sealed class FrameAnalyzerService : IDisposable _numClasses = outputMeta.Dimensions.Length >= 2 ? outputMeta.Dimensions[1] - 4 : 80; _logger.LogInformation( - "FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes})", - _modelPath, _inputName, _numClasses); + "FrameAnalyzer initialized with model: {ModelPath} (input: {InputName}, classes: {Classes}, execution provider: {ExecutionProvider})", + _modelPath, _inputName, _numClasses, _executionProvider); } catch (Exception ex) { @@ -166,9 +166,14 @@ public sealed class FrameAnalyzerService : IDisposable _processingLoop = Task.Run(() => ProcessingLoopAsync(_cts.Token)); } - private InferenceSession CreateSession(string modelPath, string requestedProvider, out string actualProvider) + private InferenceSession CreateSession(string modelPath, string requestedProvider, bool cudaDeviceAvailable, out string actualProvider) { - var availableProviders = OrtEnv.Instance().GetAvailableProviders(); + // Do not initialize/enumerate native CUDA providers when hardware detection + // says no NVIDIA device is attached; some ORT GPU builds can fault inside + // native provider discovery before managed fallback handling is possible. + var availableProviders = cudaDeviceAvailable + ? OrtEnv.Instance().GetAvailableProviders() + : Array.Empty(); return OnnxExecutionProviderSelection.CreateSession( requestedProvider, availableProviders, @@ -187,7 +192,8 @@ public sealed class FrameAnalyzerService : IDisposable reason => _logger.LogWarning( "CUDA ONNX execution provider could not be used ({Reason}); falling back to CPU", reason), - out actualProvider); + out actualProvider, + cudaDeviceAvailable); } private static void ConfigureSessionOptions(OnnxSessionOptions options) diff --git a/src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs b/src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs index 672ad3d..3e783a7 100644 --- a/src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs +++ b/src/Heimdall.Agent/Services/OnnxExecutionProviderSelection.cs @@ -12,7 +12,8 @@ internal static class OnnxExecutionProviderSelection Func createCudaSession, Func createCpuSession, Action reportFallback, - out string actualProvider) + out string actualProvider, + bool cudaDeviceAvailable = true) where TSession : class { ArgumentNullException.ThrowIfNull(availableProviders); @@ -22,7 +23,11 @@ internal static class OnnxExecutionProviderSelection if (string.Equals(requestedProvider, "CUDA", StringComparison.OrdinalIgnoreCase)) { - if (availableProviders.Contains(CudaProviderName, StringComparer.Ordinal)) + if (!cudaDeviceAvailable) + { + reportFallback("No NVIDIA CUDA device was detected by the Agent"); + } + else if (availableProviders.Contains(CudaProviderName, StringComparer.Ordinal)) { try { diff --git a/src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor b/src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor index c430a1f..cafc1be 100644 --- a/src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor +++ b/src/Heimdall.Web/Components/Pages/Admin/GroupsPage.razor @@ -126,22 +126,41 @@ else @Text["AdminGroups_AddMember"]
- + + @foreach (var user in _availableMembers) + { + @user.DisplayName (@user.Email) + } + + Disabled="@(_savingMember || _selectedMemberUserId is null)"> @if (_savingMember) { } @Text["AdminGroups_Add"]
- @if (!string.IsNullOrEmpty(_memberUserId)) + + + @Text["AdminGroups_MemberName"] + @Text["AdminGroups_MemberEmail"] + @Text["AdminGroups_Actions"] + + + @context.DisplayName + @context.Email + + + + + @Text["AdminGroups_NoMembers"] + + + @if (_groupMembers.Count > 0) { - - @if (_savingMember) { } - @Text["AdminGroups_RemoveMember"] - + @string.Format(Text["AdminGroups_MemberCount"], _groupMembers.Count) }
@@ -276,9 +295,11 @@ else private string _editError = ""; // Member management - private string _memberUserId = ""; + private Guid? _selectedMemberUserId; + private List _allUsers = []; + private List _availableMembers = []; + private List _groupMembers = []; private bool _savingMember; - private bool DisabledAddMember => _savingMember || string.IsNullOrWhiteSpace(_memberUserId); // Group camera access private List _sites = []; @@ -357,7 +378,7 @@ else _editGroup = group; _editName = group.Name; _editDescription = group.Description ?? ""; - _memberUserId = ""; + _selectedMemberUserId = null; _editError = ""; _groupCameraError = false; _selectedGroupCameraId = null; @@ -407,6 +428,21 @@ else } _groupCameras = granted; UpdateAvailableGroupCameras(); + + var members = await Api.GetGroupMembersAsync(_editGroup.Id); + if (members is null) throw new InvalidOperationException("Could not load group members."); + _groupMembers = members.ToList(); + var users = new List(); + for (var page = 1; ; page++) + { + var result = await Api.GetUsersAsync(page, 100); + if (result is null) throw new InvalidOperationException("Could not load users."); + users.AddRange(result.Items); + if (users.Count >= result.TotalCount || result.Items.Count == 0) break; + } + _allUsers = users; + UpdateAvailableMembers(); + _editGroup.MemberCount = _groupMembers.Count; } catch { @@ -495,20 +531,15 @@ else private async Task AddMember() { - if (_editGroup is null || string.IsNullOrWhiteSpace(_memberUserId)) return; + if (_editGroup is null || _selectedMemberUserId is not Guid userId) return; _savingMember = true; try { - if (!Guid.TryParse(_memberUserId.Trim(), out var userId)) - { - Snackbar.Add(Text["AdminGroups_InvalidUserId"], Severity.Error); - return; - } var success = await Api.AddUserToGroupAsync(_editGroup.Id, userId); if (success) { - _editGroup!.MemberCount++; - _memberUserId = ""; + _selectedMemberUserId = null; + await LoadGroupMembersAsync(); Snackbar.Add(Text["AdminGroups_AddMemberSuccess"], Severity.Success); } else @@ -520,22 +551,16 @@ else finally { _savingMember = false; } } - private async Task RemoveMember() + private async Task RemoveMember(Guid userId) { - if (_editGroup is null || string.IsNullOrWhiteSpace(_memberUserId)) return; + if (_editGroup is null) return; _savingMember = true; try { - if (!Guid.TryParse(_memberUserId.Trim(), out var userId)) - { - Snackbar.Add(Text["AdminGroups_InvalidUserId"], Severity.Error); - return; - } var success = await Api.RemoveUserFromGroupAsync(_editGroup.Id, userId); if (success) { - _editGroup!.MemberCount = Math.Max(0, _editGroup!.MemberCount - 1); - _memberUserId = ""; + await LoadGroupMembersAsync(); Snackbar.Add(Text["AdminGroups_RemoveMemberSuccess"], Severity.Success); } else @@ -547,6 +572,23 @@ else finally { _savingMember = false; } } + private async Task LoadGroupMembersAsync() + { + if (_editGroup is null) return; + var members = await Api.GetGroupMembersAsync(_editGroup.Id); + if (members is null) throw new InvalidOperationException("Could not reload group members."); + _groupMembers = members.ToList(); + UpdateAvailableMembers(); + _editGroup.MemberCount = _groupMembers.Count; + } + + private void UpdateAvailableMembers() + { + var memberIds = _groupMembers.Select(member => member.UserId).ToHashSet(); + _availableMembers = _allUsers.Where(user => !memberIds.Contains(user.Id)) + .OrderBy(user => user.DisplayName, StringComparer.CurrentCultureIgnoreCase).ToList(); + } + // ─── Delete ─────────────────────────────────────────────────── private void OpenDelete(GroupItem group) diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 2c32313..5e00620 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -1644,6 +1644,18 @@ Remove camera access from the group + + Select a user + + + Name + + + Email + + + No users in this group. + Remove member diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 10ae671..7773b7a 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -1644,6 +1644,18 @@ Retirer l'accès caméra du groupe + + Sélectionner un utilisateur + + + Nom + + + E-mail + + + Aucun utilisateur dans ce groupe. + Retirer le membre diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index 738dfe1..a2306e9 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -1644,6 +1644,18 @@ Retirer l'accès caméra du groupe + + Select a user + + + Name + + + Email + + + No users in this group. + Retirer le membre diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 233b85d..0542169 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -218,11 +218,17 @@ public class HeimdallApiClient : IDisposable public async Task AddUserToGroupAsync(Guid groupId, Guid userId) { var client = CreateClient(); - var response = await client.PostAsJsonAsync($"api/groups/{groupId}/users", - new { userId }, Json); + var response = await client.PostAsync($"api/groups/{groupId}/users/{userId}", content: null); return response.IsSuccessStatusCode; } + public async Task?> GetGroupMembersAsync(Guid groupId) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/groups/{groupId}/users", Json); + } + public async Task RemoveUserFromGroupAsync(Guid groupId, Guid userId) { var client = CreateClient(); @@ -1397,6 +1403,8 @@ public class GroupItem public int MemberCount { get; set; } } +public record GroupMemberItem(Guid UserId, string Email, string DisplayName); + // ─── Notification Config DTOs ───────────────────────────────────────── public class NotificationConfigItem diff --git a/tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs b/tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs index 8c0da79..174c860 100644 --- a/tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs +++ b/tests/Heimdall.Agent.Tests/OnnxExecutionProviderSelectionTests.cs @@ -74,4 +74,25 @@ public sealed class OnnxExecutionProviderSelectionTests fallbacks.ShouldContain(nameof(DllNotFoundException)); actualProvider.ShouldBe(OnnxExecutionProviderSelection.CpuProviderName); } + [Fact] + public void CreateSession_CudaDeviceUnavailable_FallsBackWithoutTryingCuda() + { + var cudaCalls = 0; + var fallbacks = new List(); + + var session = OnnxExecutionProviderSelection.CreateSession( + "CUDA", + [OnnxExecutionProviderSelection.CudaProviderName, OnnxExecutionProviderSelection.CpuProviderName], + () => { cudaCalls++; return "cuda"; }, + () => "cpu", + fallbacks.Add, + out var actualProvider, + cudaDeviceAvailable: false); + + session.ShouldBe("cpu"); + cudaCalls.ShouldBe(0); + fallbacks.ShouldContain("No NVIDIA CUDA device was detected by the Agent"); + actualProvider.ShouldBe(OnnxExecutionProviderSelection.CpuProviderName); + } + } diff --git a/tests/Heimdall.IntegrationTests/Scenarios/CameraAuthorizationScenarios.cs b/tests/Heimdall.IntegrationTests/Scenarios/CameraAuthorizationScenarios.cs index c39ed40..772876e 100644 --- a/tests/Heimdall.IntegrationTests/Scenarios/CameraAuthorizationScenarios.cs +++ b/tests/Heimdall.IntegrationTests/Scenarios/CameraAuthorizationScenarios.cs @@ -70,6 +70,68 @@ public sealed class CameraAuthorizationScenarios : PostgresTestBase (await viewer.GetAsync($"api/assignments/camera/{allowedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); } + [Fact] + public async Task Direct_and_group_grants_form_a_live_union_and_revocation_preserves_other_grants() + { + var admin = await Factory.CreateAdminClientAsync(); + var viewer = await Factory.CreateViewerClientAsync(admin); + var viewerId = UserIdFromAccessToken(viewer); + + var siteResponse = await admin.PostAsJsonAsync("api/sites", new + { + name = $"Group access {Guid.NewGuid():N}", + timezone = "UTC" + }); + siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var siteId = (await siteResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + + var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name = "Group granted camera", + rtspUrl = "rtsp://127.0.0.1:554/group-test" + }); + cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var cameraId = (await cameraResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + + var groupResponse = await admin.PostAsJsonAsync("api/groups", new + { + name = $"Camera viewers {Guid.NewGuid():N}" + }); + groupResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var groupId = (await groupResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + + (await admin.PostAsync($"api/groups/{groupId}/users/{viewerId}", content: null)) + .StatusCode.ShouldBe(HttpStatusCode.OK); + (await admin.PostAsJsonAsync($"api/groups/{groupId}/cameras", new { groupId, cameraId })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{cameraId}")).StatusCode.ShouldBe(HttpStatusCode.OK); + + var directGrantResponse = await admin.PostAsJsonAsync("api/user-camera-access", new + { + userId = viewerId, + siteId, + cameraId + }); + directGrantResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var directGrantId = (await directGrantResponse.Content.ReadFromJsonAsync()) + .GetProperty("id").GetGuid(); + + (await admin.DeleteAsync($"api/groups/{groupId}/users/{viewerId}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{cameraId}")).StatusCode.ShouldBe(HttpStatusCode.OK, + "the remaining direct grant continues to authorize the camera"); + + (await admin.DeleteAsync($"api/user-camera-access/{directGrantId}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{cameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + + (await admin.PostAsync($"api/groups/{groupId}/users/{viewerId}", content: null)) + .StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{cameraId}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await admin.DeleteAsync($"api/groups/{groupId}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{cameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden, + "soft deleting a group revokes its camera grants immediately"); + } + private static Guid UserIdFromAccessToken(HttpClient client) { var token = client.DefaultRequestHeaders.Authorization?.Parameter diff --git a/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs index 289a398..54cd8bd 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/GroupsPageTests.cs @@ -131,10 +131,12 @@ public class GroupsPageTests : PageTestBase var cameraId = Guid.NewGuid(); var site = new SiteItem(siteId, "Site Lyon", null, "Europe/Paris", null, true, false, DateTime.UtcNow); var camera = new CameraItem { Id = cameraId, SiteId = siteId, Name = "Entrée", Status = "Online" }; - Handler.OnGet("api/groups", new PagedData([Group()], 1, 1, 20)); - Handler.OnGet("api/sites", new PagedData([site], 1, 1, 100)); - Handler.OnGet($"api/cameras/by-site/{siteId}", new PagedData([camera], 1, 1, 100)); Handler.OnGet($"api/groups/{GroupId}/cameras", new PagedData([], 0, 1, 100)); + Handler.OnGet($"api/groups/{GroupId}/users", Array.Empty()); + Handler.OnGet($"api/cameras/by-site/{siteId}", new PagedData([camera], 1, 1, 100)); + Handler.OnGet("api/sites", new PagedData([site], 1, 1, 100)); + Handler.OnGet("api/users", new PagedData([], 0, 1, 100)); + Handler.OnGet("api/groups", new PagedData([Group()], 1, 1, 20)); Handler.On(HttpMethod.Post, $"api/groups/{GroupId}/cameras", System.Net.HttpStatusCode.OK); Handler.On(HttpMethod.Delete, $"api/groups/{GroupId}/cameras/{cameraId}", System.Net.HttpStatusCode.OK); LoginAs(); @@ -166,4 +168,36 @@ public class GroupsPageTests : PageTestBase cut.WaitForAssertion(() => Handler.Requests.ShouldContain(request => request.Method == HttpMethod.Delete && request.RequestUri!.AbsolutePath == $"/api/groups/{GroupId}/cameras/{cameraId}")); } + + [Fact] + public async Task GroupsPage_AfficheEtRetireUnMembreAvecSonIdentite() + { + var userId = Guid.NewGuid(); + var user = new UserItem { Id = userId, DisplayName = "Camille Martin", Email = "camille@example.test" }; + var member = new GroupMemberItem(userId, user.Email, user.DisplayName); + Handler.OnGet($"api/groups/{GroupId}/cameras", new PagedData([], 0, 1, 100)); + Handler.OnGet($"api/groups/{GroupId}/users", new[] { member }); + Handler.OnGet("api/users", new PagedData([], 0, 1, 100)); + Handler.OnGet("api/sites", new PagedData([], 0, 1, 100)); + Handler.OnGet("api/groups", new PagedData([Group()], 1, 1, 20)); + Handler.On(HttpMethod.Delete, $"api/groups/{GroupId}/users/{userId}", System.Net.HttpStatusCode.OK); + LoginAs(); + + var cut = RenderPage(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Opérateurs")); + cut.FindAll("button.mud-icon-button") + .Single(button => button.GetAttribute("aria-label") == "Modifier le groupe").Click(); + cut.WaitForAssertion(() => + { + cut.Markup.Contains("Camille Martin").ShouldBeTrue( + string.Join(";", Handler.Requests.Select(request => request.RequestUri?.PathAndQuery))); + cut.Markup.ShouldContain("camille@example.test"); + }); + var removeButton = cut.FindAll("button.mud-icon-button") + .Single(button => button.GetAttribute("title") == "Retirer le membre"); + await cut.InvokeAsync(() => removeButton.Click()); + + Handler.Requests.ShouldContain(request => request.Method == HttpMethod.Delete + && request.RequestUri!.AbsolutePath == $"/api/groups/{GroupId}/users/{userId}"); + } } diff --git a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs index d66808f..8a3be13 100644 --- a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs +++ b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientTests.cs @@ -164,10 +164,30 @@ public sealed class HeimdallApiClientTests : IDisposable { SetAuthToken(); _handler.QueueResponse(HttpStatusCode.OK); + var groupId = Guid.NewGuid(); + var userId = Guid.NewGuid(); - var result = await _sut.AddUserToGroupAsync(Guid.NewGuid(), Guid.NewGuid()); + var result = await _sut.AddUserToGroupAsync(groupId, userId); Assert.True(result); + Assert.Equal(HttpMethod.Post, _handler.LastRequest!.Method); + Assert.Equal($"http://localhost:8080/api/groups/{groupId}/users/{userId}", _handler.LastRequest.RequestUri!.AbsoluteUri); + Assert.Null(_handler.LastRequest.Content); + } + + [Fact] + public async Task GetGroupMembersAsync_ReturnsMembersFromTheGroupsEndpoint() + { + SetAuthToken(); + var groupId = Guid.NewGuid(); + var userId = Guid.NewGuid(); + _handler.QueueResponse(HttpStatusCode.OK, new[] { new GroupMemberItem(userId, "viewer@example.test", "Viewer") }); + + var result = await _sut.GetGroupMembersAsync(groupId); + + Assert.Equal(userId, Assert.Single(result!).UserId); + Assert.Equal(HttpMethod.Get, _handler.LastRequest!.Method); + Assert.Equal($"http://localhost:8080/api/groups/{groupId}/users", _handler.LastRequest.RequestUri!.AbsoluteUri); } [Fact] diff --git a/todo.md b/todo.md index 6680c6e..d0eecf1 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] Vérifier en exécution la publication Docker Hub des images serveur `eltruncho/heimdall` et agent `eltruncho/heimdall-agent` après merge sur `main`, avec les tags `latest` et `sha-`. Les runs main #227 (`e4dc00ca`) et #243 (`d59b546b`, 24 octobre 2026) ont réussi les deux builds/scans et le job « Publish Docker Hub latest tags » ; ces publications confirment que les secrets utilisés par ce workflow sont opérationnels. - [ ] Valider la publication signée de release de bout en bout. Le 4 novembre 2026, l’API Gitea a confirmé que `RELEASE_SERVER_URL` existe et correspond à l’origine de la forge; `.gitea/workflows/build.yml` compare cette valeur à `BUILD_SERVER_URL` avant toute publication. Le 4 novembre, `python3 scripts/ci/accept-release-offline.py` a exécuté les vrais `package.sh` et `publish.sh` avec clé ECDSA P-256 synthétique, faux Docker CLI et API Gitea TLS sur loopback : archives Web/Agent construites, signature du manifeste vérifiée, sommes de contrôle, digests, 4 pushes simulés et 9 assets du brouillon vérifiés. Aucun service distant ni Docker réel n’a été contacté. Le parcours restant comprend les secrets du registre Gitea, la clé Actions ECDSA, les images Docker Hub `eltruncho/heimdall` / `eltruncho/heimdall-agent`, un run tagué créant le brouillon, puis installation et rollback Agent sur hôtes réels. Voir `skills/release-automation/SKILL.md`. - [x] Ne pas publier les rapports CI comme artefacts distants : aucun job actuel ne les consomme après le contrôle de couverture dans `verify`, et l'échec historique `CreateArtifact: EHOSTUNREACH` ne justifie pas de dépendre du service runner. Les fichiers `artifacts/` restent locaux au job pour les tests, les rapports de sécurité et le packaging ; ils ne sont pas téléversés. -- [ ] **Renovate** Le run planifié #401 (2 novembre 2026) échoue dans l’initialisation Renovate avec `Authentication failure`, après que le contrôle de présence du secret a réussi. La vérification des journaux et de l’API ne révèle pas la valeur ni la portée du secret `RENOVATE_TOKEN`; l’API Actions consultée expose `RELEASE_SERVER_URL`, mais pas le secret. Une prévalidation a été ajoutée dans cette branche : vérification HTTPS de `GITEA_API_ENDPOINT`, appel authentifié `/user` et lecture du dépôt cible, avec statut HTTP sans fuite de jeton. Tests Node locaux 4/4; le test Compose jetable est à refaire car le pull de `node:22-alpine` est resté bloqué, sans conteneur ni volume résiduel. Restent à corriger/valider le secret bot à distance et obtenir un run Renovate réussi avec accès d’écriture confirmé. Voir `skills/renovate-automation/SKILL.md`. +- [ ] **Renovate** Le run planifié #401 (2 novembre 2026) échoue dans l’initialisation Renovate avec `Authentication failure`, après que le contrôle de présence du secret a réussi. La vérification des journaux et de l’API ne révèle pas la valeur ni la portée du secret `RENOVATE_TOKEN`; l’API Actions consultée expose `RELEASE_SERVER_URL`, mais pas le secret. Une prévalidation a été ajoutée dans cette branche : vérification HTTPS de `GITEA_API_ENDPOINT`, appel authentifié `/user` et lecture du dépôt cible, avec statut HTTP sans fuite de jeton. Tests Node locaux 4/4. Le 4 novembre 2026, Compose jetable sans port publié ni volume persistant a testé le précontrôle contre une API Gitea HTTPS mockée et un certificat local explicitement approuvé : jeton synthétique accepté pour `/user` et le dépôt; mauvais jeton refusé HTTP 401 sans fuite. Conteneur et réseau supprimés, aucun volume ne subsiste. Restent à corriger/valider le secret bot distant et obtenir un run Renovate réussi avec accès d’écriture confirmé. Voir `skills/renovate-automation/SKILL.md`. - [x] Vérifier la protection de `main` : Gitea interdit les pushes directs et les force-pushes, empêche l'override administrateur de merge, et exige `Heimdall Gitea / CI policy (pull_request)`. Le run PR #305 a validé ce job après les tests et les scans ; le run documentaire #309 a réussi avec les builds lourds ignorés. La PR temporaire rouge #98 (run #311) a fait échouer le détecteur et `CI policy`, puis l'API de merge a répondu HTTP 405 « Not all required status checks successful ». La PR de test a été fermée et sa branche supprimée. - [x] Réduire les restaurations répétées : après le restore verrouillé du build, le scan NuGet réutilise les assets avec `security.sh dependencies --no-restore`; l'appel autonome conserve le restore par défaut. Sur le même runner `runner-murin`, la porte NuGet a duré 51 s avant l'optimisation (run main #227) et 36 s sur la PR #71, puis 29 s et 31 s sur `main` après merge (runs #230/#239/#243). La médiane après changement est 31 s, soit 20 s de moins (39 %) que la mesure de référence ; les durées CI restent indicatives, les conditions de cache et de charge n'étant pas contrôlées. @@ -44,14 +44,14 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. -- [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. +- [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. Un vertical initial ajoute le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read Data Protection à durée limitée, la revalidation des droits caméra et un lecteur WHEP dans le détail caméra ; audio/PTZ restent exclus. Les builds/tests ciblés API/Web (7 tests) et Agent (1 test), la syntaxe JS et `git diff --check` passent. La recette Compose jetable a validé bootstrap admin/site, enregistrement Agent, caméra RTSP synthétique assignée/activée, demande publish-session et démarrage du relais, ticket read autorisé + callback MediaMTX 200, rejet ticket forgé 401 et rejet caméra inconnue. Une requête WHEP avec SDP invalide a atteint MediaMTX et retourné 400; aucun navigateur/frame décodée ni arrêt par désactivation API n’a été vérifié. Compose `hmd-webrtc-e9e542` a été arrêté avec `down --volumes --remove-orphans`, puis ses conteneurs, volumes et réseaux vérifiés absents; les secrets/cache acceptance ont été supprimés. Validation caméra physique, LAN, TURN externe, lecture d’une vraie offre SDP et cycle désactivation restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d'inventaire restent distincts. L’Agent possède un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d'image GPU intégré au manifeste ECDSA de release, un choix CPU/CUDA dans l’installateur Docker et la conservation de ce variant pendant les mises à jour. CPU reste le défaut. Validation locale : restores CPU/GPU verrouillés; builds Agent CPU/GPU; 4 tests de sélection/fallback, 2 tests de signature image CPU/GPU et inférence réelle CPU du modèle avec le package GPU; 10 tests Web `SiteDetailTests` couvrent Compose CPU sans device et Compose/Docker Run CUDA avec digest. L'acceptation offline de release signée a passé : manifeste CPU/GPU, digests, 10 assets, sommes et signature ECDSA, six pushes simulés, sans contacter Docker ni Gitea/Hub réels. Les tests de configuration Compose et scripts vérifient le runtime sans GPU. Restent le build + recette Compose jetable après créneau Docker et l'exécution sur matériel NVIDIA réel; aucun GPU réel n'est déclaré validé. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Après correctif, un conteneur basé sur CUDA sans device a répondu 200 sur `/health/live`, mais une publication Agent CPU bind-mountée masquait ses bibliothèques ONNX GPU; l’absence de Central/token a aussi interrompu l’enregistrement. Cela valide le garde-fou startup, pas le paquet GPU final. Restent rebuild de l’image GPU post-correctif, acceptation avec Central + token et preuve d’inférence CPU sans device, puis GPU NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. -- [ ] **UI groupes #138 / accès #134** L'édition des groupes permet maintenant de lister les caméras des sites, d'accorder/révoquer les accès de groupe et d'afficher les noms de site/caméra via l'API existante. Restent la validation produit et la vérification de l'union accès direct/groupe ainsi que des priorités dans l'interface. +- [x] **UI groupes #138 / accès #134** L’éditeur permet de parcourir les comptes par nom/e-mail, de lister et retirer les membres, et d’accorder/révoquer les accès caméra avec nom de caméra et site. Le 4 novembre 2026, la revue a trouvé puis corrigé le POST membre qui visait une route inexistante; le client utilise désormais `POST /api/groups/{groupId}/users/{userId}` et `GET /api/groups/{groupId}/users`. Vérifications : Web groupes + client API 39/39; matrice d’autorisation Web 14/14; CameraAccessService Infrastructure 25/25; scénario PostgreSQL relationnel 1/1 valide l’union direct/groupe, le maintien du droit restant après révocation de l’autre, puis l’arrêt du grant d’un groupe supprimé. Recette Compose source jetable : bootstrap Admin, création groupe, ajout/liste/retrait membre et liste vide, tous HTTP 200; conteneurs, volumes, réseau et secrets temporaires vérifiés supprimés. Skill : `skills/group-access/SKILL.md`. - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; reste une validation de scraping sur un déploiement et l'évolution réelle des mesures. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. -- 2.54.1 From 3208bc93feaf7b608e17ce89aaa040ade22b07c4 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 11:02:41 +0100 Subject: [PATCH 16/40] feat: complete local camera and operations acceptance --- docker/Dockerfile | 2 +- docker/backup/README.md | 3 +- .../docker-compose.agent.dev.gpu-nvidia.yml | 5 +- docker/docker-compose.backup.yml | 5 +- docker/docker-compose.prod.yml | 1 + docker/docker-compose.webrtc-local-test.yml | 6 +- docker/docker-compose.webrtc.yml | 2 + docker/docker-compose.yml | 1 + docker/mediamtx.yml | 4 +- docker/scripts/backup-protected-data.sh | 11 +- docker/scripts/backup-rustfs.sh | 12 +- docker/scripts/backup.sh | 11 +- docker/scripts/restore.sh | 2 +- docs/docker-compose.md | 10 + scripts/ci/test_ci.py | 3 + skills/agent-runtime-acceptance/SKILL.md | 5 +- skills/backup-restore/SKILL.md | 4 +- skills/gpu-inference/SKILL.md | 2 +- skills/mdns-camera-discovery/SKILL.md | 27 +++ skills/video-recording/SKILL.md | 6 +- skills/vision-identity/SKILL.md | 44 ++-- skills/webrtc-live/SKILL.md | 2 +- .../Services/NetworkCameraScanner.cs | 2 +- .../Common/IRecordingQuotaGuard.cs | 14 ++ .../UploadRecording/UploadRecordingCommand.cs | 115 ++++++++-- .../Services/ILicensePlateOcr.cs | 18 ++ .../DependencyInjection.cs | 7 +- .../LicensePlateRecognitionService.cs | 50 +++++ .../Services/TesseractPlateOcr.cs | 150 +++++++++++++ .../Storage/RecordingQuotaGuard.cs | 43 ++++ .../Storage/RecordingStorageQuotaOptions.cs | 13 ++ src/Heimdall.Mdns/AssemblyInfo.cs | 3 + src/Heimdall.Mdns/MdnsClient.cs | 16 +- .../Components/Pages/CameraDetail.razor | 47 ++++ .../Components/Pages/EventsPage.razor | 2 + .../Controllers/PlateRecognitionController.cs | 48 +++++ .../Localization/SharedResources.en.resx | 4 + .../Localization/SharedResources.fr.resx | 4 + .../Localization/SharedResources.resx | 4 + .../Services/HeimdallApiClient.cs | 17 ++ src/Heimdall.Web/wwwroot/js/live-view.js | 2 +- .../ConfigReceiverServiceTests.cs | 80 ++++--- .../HomeKitMdnsProbeTests.cs | 162 +++++++++++++- .../Fixtures/synthetic-plate.png | Bin 0 -> 13575 bytes .../Heimdall.Infrastructure.Tests.csproj | 6 +- .../PlateOcrTests.cs | 44 ++++ .../RecordingStorageQuotaOptionsTests.cs | 27 +++ .../Controllers/PostgresTestBase.cs | 2 +- .../Controllers/RecordingQuotaTests.cs | 200 ++++++++++++++++++ .../HeimdallWebApplicationFactory.cs | 11 +- .../PlateRecognitionControllerTests.cs | 26 +++ todo.md | 14 +- 52 files changed, 1193 insertions(+), 106 deletions(-) create mode 100644 skills/mdns-camera-discovery/SKILL.md create mode 100644 src/Heimdall.Application/Common/IRecordingQuotaGuard.cs create mode 100644 src/Heimdall.Application/Services/ILicensePlateOcr.cs create mode 100644 src/Heimdall.Infrastructure/Services/LicensePlateRecognitionService.cs create mode 100644 src/Heimdall.Infrastructure/Services/TesseractPlateOcr.cs create mode 100644 src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs create mode 100644 src/Heimdall.Infrastructure/Storage/RecordingStorageQuotaOptions.cs create mode 100644 src/Heimdall.Mdns/AssemblyInfo.cs create mode 100644 src/Heimdall.Web/Controllers/PlateRecognitionController.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/Fixtures/synthetic-plate.png create mode 100644 tests/Heimdall.Infrastructure.Tests/PlateOcrTests.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/Storage/RecordingStorageQuotaOptionsTests.cs create mode 100644 tests/Heimdall.IntegrationTests/Controllers/RecordingQuotaTests.cs create mode 100644 tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs diff --git a/docker/Dockerfile b/docker/Dockerfile index 89b54cf..1801e0e 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -10,7 +10,7 @@ RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee WORKDIR /app -RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata && rm -rf /var/lib/apt/lists/* +RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng && rm -rf /var/lib/apt/lists/* ENV ASPNETCORE_URLS=http://+:8080 COPY --from=build /out/ ./ EXPOSE 8080 diff --git a/docker/backup/README.md b/docker/backup/README.md index c6a8e0d..9e16286 100644 --- a/docker/backup/README.md +++ b/docker/backup/README.md @@ -22,7 +22,8 @@ docker compose --env-file .env -f docker-compose.backup.yml up -d Le Central et PostgreSQL doivent d'abord être démarrés. Le service `backup` rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine -avec crontab interne. Les dumps sont stockés dans `backup_data`; l'upload +avec crontab interne, AWS CLI et GNU coreutils (pour le calcul portable des seuils +de rétention Alpine). Les dumps sont stockés dans `backup_data`; l'upload RustFS/S3 est facultatif. Le service monte aussi le volume `heimdall_data` du Compose Central : les objets stockés localement et les clés Data Protection sont archivés ensemble. diff --git a/docker/docker-compose.agent.dev.gpu-nvidia.yml b/docker/docker-compose.agent.dev.gpu-nvidia.yml index d02f6f7..f52e4b3 100644 --- a/docker/docker-compose.agent.dev.gpu-nvidia.yml +++ b/docker/docker-compose.agent.dev.gpu-nvidia.yml @@ -19,4 +19,7 @@ services: capabilities: [gpu] agent-state-init: - image: heimdall-agent:local + image: heimdall-agent:gpu-local + build: + context: .. + dockerfile: docker/Dockerfile.agent.gpu diff --git a/docker/docker-compose.backup.yml b/docker/docker-compose.backup.yml index 0bf4cc5..9012987 100644 --- a/docker/docker-compose.backup.yml +++ b/docker/docker-compose.backup.yml @@ -30,10 +30,9 @@ services: entrypoint: ["/bin/sh", "-c"] command: - | + set -e export POSTGRES_PASSWORD="$$(cat /run/secrets/db_password)" - apk add --no-cache curl bash >/dev/null 2>&1 || true - curl -fsSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc || true - chmod +x /usr/local/bin/mc 2>/dev/null || true + apk add --no-cache aws-cli bash coreutils echo '0 2 * * * bash /scripts/backup.sh >> /var/log/backup.log 2>&1' > /tmp/crontab.txt echo '15 2 * * * bash /scripts/backup-protected-data.sh >> /var/log/backup-protected-data.log 2>&1' >> /tmp/crontab.txt echo '0 3 * * 0 bash /scripts/backup-rustfs.sh >> /var/log/backup-rustfs.log 2>&1' >> /tmp/crontab.txt diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index 932c387..8adb32f 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -53,6 +53,7 @@ services: LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} + Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776} Sentry__Dsn: ${SENTRY_DSN:-} Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05} Sentry__Release: ${SENTRY_RELEASE:-} diff --git a/docker/docker-compose.webrtc-local-test.yml b/docker/docker-compose.webrtc-local-test.yml index 5ae6683..037d78f 100644 --- a/docker/docker-compose.webrtc-local-test.yml +++ b/docker/docker-compose.webrtc-local-test.yml @@ -7,10 +7,14 @@ services: HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin} MTX_AUTHMETHOD: http MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central callback URL} + MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin} + # The browser receives this ICE port in SDP; keep the published host port + # identical so Docker NAT does not advertise an unreachable container port. + MTX_WEBRTCLOCALUDPADDRESS: :${HEIMDALL_TEST_ICE_PORT:-18189} ports: - "127.0.0.1:${HEIMDALL_TEST_PUBLISH_PORT:-18555}:8554/tcp" - "127.0.0.1:${HEIMDALL_TEST_WHEP_PORT:-18889}:8889/tcp" - - "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:8189/udp" + - "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:${HEIMDALL_TEST_ICE_PORT:-18189}/udp" volumes: - ./mediamtx.local-test.yml:/mediamtx.yml:ro networks: diff --git a/docker/docker-compose.webrtc.yml b/docker/docker-compose.webrtc.yml index 4fd8ede..8f5fce3 100644 --- a/docker/docker-compose.webrtc.yml +++ b/docker/docker-compose.webrtc.yml @@ -9,6 +9,8 @@ services: HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin} MTX_AUTHMETHOD: http MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central MediaMTX callback URL} + MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin} + MTX_WEBRTCADDITIONALHOSTS: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname} ports: - "${HEIMDALL_RTSPS_PORT:-8322}:8322/tcp" - "${HEIMDALL_WHEP_PORT:-8889}:8889/tcp" diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index b5a4177..164655c 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -43,6 +43,7 @@ services: LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-} LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} + Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776} ports: - "${WEB_PORT:-5000}:8080" volumes: diff --git a/docker/mediamtx.yml b/docker/mediamtx.yml index a60015a..4001019 100644 --- a/docker/mediamtx.yml +++ b/docker/mediamtx.yml @@ -11,9 +11,9 @@ webrtcAddress: :8889 webrtcEncryption: true webrtcServerCert: /certs/server.crt webrtcServerKey: /certs/server.key -webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}'] +webrtcAllowOrigins: [] webrtcLocalUDPAddress: :8189 -webrtcAdditionalHosts: ['${HEIMDALL_WEBRTC_PUBLIC_HOST}'] +webrtcAdditionalHosts: [] pathDefaults: source: publisher diff --git a/docker/scripts/backup-protected-data.sh b/docker/scripts/backup-protected-data.sh index c6a90cd..9957da4 100755 --- a/docker/scripts/backup-protected-data.sh +++ b/docker/scripts/backup-protected-data.sh @@ -35,9 +35,14 @@ find "$ARCHIVE_DIR" -type f -name 'heimdall-data-*.tar.gz' -mtime "+$RETENTION_D if [[ "$SKIP_S3_UPLOAD" == "1" ]]; then log "S3 upload disabled by BACKUP_SKIP_S3_UPLOAD" elif [[ -n "$S3_ENDPOINT" && -n "$S3_ACCESS_KEY" && -n "$S3_SECRET_KEY" ]]; then - command -v mc >/dev/null 2>&1 || die "mc is required to upload protected data backups" - mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null - mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")" + if command -v mc >/dev/null 2>&1; then + mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null + mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")" + elif command -v aws >/dev/null 2>&1; then + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$ARCHIVE" "s3://${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")" + else + die "Neither mc nor aws CLI is available to upload protected data backups" + fi log "Uploaded protected data archive to the configured object store" else log "S3 credentials are not configured; the archive remains in the local backup volume" diff --git a/docker/scripts/backup-rustfs.sh b/docker/scripts/backup-rustfs.sh index a9b87fb..25e1023 100755 --- a/docker/scripts/backup-rustfs.sh +++ b/docker/scripts/backup-rustfs.sh @@ -76,7 +76,7 @@ else 2>&1 | tail -10 else # AWS CLI: sync with exclusion - aws --endpoint-url "$S3_ENDPOINT" s3 sync \ + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 sync \ "s3://${S3_BUCKET}" \ "s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \ --exclude "backup/*" \ @@ -102,6 +102,14 @@ if [[ -n "$CUTOFF_WEEK" ]]; then mc rm --recursive --force "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" 2>/dev/null || true fi done + else + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${BACKUP_PREFIX}/" 2>/dev/null | awk '$1 == "PRE" {print $2}' | while read -r week; do + week="${week%/}" + if [[ "$week" < "$CUTOFF_WEEK" ]]; then + log " Deleting: ${BACKUP_PREFIX}/${week}/" + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm --recursive "s3://${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" >/dev/null + fi + done fi fi fi @@ -131,7 +139,7 @@ Total: ${TOTAL_SIZE} bytes if [[ "$CLIENT" == "mc" ]]; then echo "$MANIFEST" | mc pipe "heimdall-backup/${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null else - echo "$MANIFEST" | aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null + echo "$MANIFEST" | AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null fi log "Manifest written: ${MANIFEST_KEY}" fi diff --git a/docker/scripts/backup.sh b/docker/scripts/backup.sh index 36f9f9e..f05e7c6 100755 --- a/docker/scripts/backup.sh +++ b/docker/scripts/backup.sh @@ -109,8 +109,8 @@ if [[ -n "$S3_ENDPOINT" ]]; then mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3 mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3 else - aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3 - aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3 + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3 + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3 fi log "Upload complete" fi @@ -141,6 +141,13 @@ if [[ -n "$S3_ENDPOINT" && "$IS_DRY_RUN" != "1" ]]; then mc rm "heimdall-backup/${S3_BUCKET}/${key}" 2>/dev/null || true fi done + elif command -v aws >/dev/null 2>&1; then + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${S3_PREFIX}/" --recursive 2>/dev/null | awk '{print $4}' | while read -r key; do + if [[ "$key" =~ ([0-9]{4}-[0-9]{2}-[0-9]{2})/ ]] && [[ "${BASH_REMATCH[1]}" < "$CUTOFF_DATE" ]]; then + log " Deleting: $key" + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm "s3://${S3_BUCKET}/${key}" >/dev/null + fi + done fi fi fi diff --git a/docker/scripts/restore.sh b/docker/scripts/restore.sh index c2ec315..3898bb0 100755 --- a/docker/scripts/restore.sh +++ b/docker/scripts/restore.sh @@ -124,7 +124,7 @@ if [[ -n "$S3_KEY" ]]; then mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null mc cp "heimdall-backup/${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3 else - aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3 + AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3 fi log "Downloaded: $(du -h "$FILE" | cut -f1)" fi diff --git a/docs/docker-compose.md b/docs/docker-compose.md index 2e1c4ae..67cc636 100644 --- a/docs/docker-compose.md +++ b/docs/docker-compose.md @@ -90,10 +90,12 @@ JWT__ISSUER=heimdall JWT__AUDIENCE=heimdall-api ASPNETCORE_ENVIRONMENT=Production WEB_PORT=5000 +RECORDING_STORAGE_QUOTA_MAX_BYTES=1099511627776 Cors__AllowedOrigins=https://heimdall.example.org EOF unset db_password # Replace the example origin above with the public origin of your Central. +# The recording quota defaults to 1 TiB (1099511627776 bytes). docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d ``` @@ -221,3 +223,11 @@ project with `down --volumes --remove-orphans`, confirm its containers, named volumes and network are gone, and delete its temporary environment/secret files. This recipe is HTTP/RTSP loopback-only; production configuration remains RTSPS and HTTPS with a trusted certificate. + +A source-built disposable acceptance on 5 November 2026 decoded a 640×360 synthetic +frame through the actual `live-view.js` module in Chromium. WHEP resource deletion +returned 200, Central session release returned 204, and disabling the camera +reduced the Agent publisher count from one to zero. The project teardown left no +containers, volumes, or network. MediaMTX origins and public ICE host must be passed +through its `MTX_WEBRTCALLOWORIGINS` and `MTX_WEBRTCADDITIONALHOSTS` environment +variables; placeholders inside `mediamtx.yml` are not expanded. diff --git a/scripts/ci/test_ci.py b/scripts/ci/test_ci.py index 4767b7f..57aa9d9 100644 --- a/scripts/ci/test_ci.py +++ b/scripts/ci/test_ci.py @@ -99,6 +99,9 @@ class GpuAgentImageTests(unittest.TestCase): self.assertIn('Agent__InferenceExecutionProvider: CUDA', compose) self.assertIn('driver: nvidia', compose) self.assertIn('capabilities: [gpu]', compose) + self.assertIn('image: heimdall-agent:gpu-local', compose) + state_init = compose.split(' agent-state-init:', 1)[1] + self.assertIn('dockerfile: docker/Dockerfile.agent.gpu', state_init) class AdvisoryTests(unittest.TestCase): def check(self, data): diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index eca9a27..0a77a66 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -12,7 +12,8 @@ Read `AGENTS.md`, the Agent item in `todo.md`, and `skills/heimdall-dotnet/SKILL - `ConfigReceiverService` fetches the complete camera settings snapshot after initial connection and reconnection; `CameraConfigStore.ReplaceCentral` validates the digest and publishes all assignments atomically. - The Central acknowledgement is keyed to that exact digest. Retry network failures and HTTP 408/429/5xx at most three times with short bounded delays; stop on permanent 4xx responses. Do not log the API key, camera URLs, configuration payload, or response body. - Keep the latest applied snapshot active when an acknowledgement is rejected. A later config reload/reconnect fetches and acknowledges the current snapshot again. -- Extend `ConfigReceiverServiceTests` with an in-memory HTTP handler that returns a transient failure before success. Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values. +- `FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt` uses an in-process Kestrel Central simulator: config GET is served once; ACK receives 503 then 204; both posts must carry the same digest; the camera snapshot change event fires once; and Central records one successful ACK. `HEIMDALL_ACK_FIXTURE_PORT` pins the listener for Compose, while the API key fixture can be injected through `HEIMDALL_ACK_FIXTURE_API_KEY`. +- Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values. ## Local checks @@ -21,7 +22,7 @@ dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-m dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore ``` -For behavior changes, build the Agent from source in a uniquely named Docker Compose project using a private isolated network, generated credentials, loopback-only ports, and project-scoped volumes. Probe `/healthz`, then tear down that project with `down --volumes --remove-orphans` and verify its containers, volumes, and network are gone. Serialize Docker acceptance when another source build is using the shared daemon. +For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. Tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source. Serialize Docker acceptance when another source build is using the shared daemon. ## Acceptance boundary diff --git a/skills/backup-restore/SKILL.md b/skills/backup-restore/SKILL.md index 37507b1..9236691 100644 --- a/skills/backup-restore/SKILL.md +++ b/skills/backup-restore/SKILL.md @@ -21,4 +21,6 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res 3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions. 4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO. 5. Tear down only the disposable project with `docker compose -p down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files. -6. Keep S3 round trips, real-volume production recovery, and production RPO/RTO open until validated on their actual service and data. +6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox). Do not rely on the retired MinIO client download URL. The scripts pass configured S3 credentials explicitly to AWS CLI for each invocation. +7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed. +8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data. diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index 47ee6cd..cbf77a3 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -27,4 +27,4 @@ Use this skill when changing ONNX Runtime packages, execution provider configura ## Current limitation -The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. Their image/Compose build acceptance and physical CUDA execution remain open until those runs succeed. +The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from source with the locked GPU package. Rendered Compose confirmed that CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A disposable Central/PostgreSQL stack passed bootstrap and `/healthz`, but Docker could not create the GPU overlay's `agent-state-init` container (stalled/conflicting create calls in the shared daemon); the Agent never started. Therefore Agent health, token registration, and an actual CPU inference from the CUDA image remain unverified. Retry the complete recipe with an available Docker daemon slot: bootstrap a disposable site, run the GPU image without NVIDIA devices, attach a synthetic RTSP source, and verify an inference observation with `CPUExecutionProvider` before teardown. The first Central attempt used a malformed synthetic Npgsql connection string and produced one GlitchTip report; the fixture was corrected and the DSN disabled for the subsequent run. It contained no production data or secrets. Physical CUDA execution also remains open. diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md new file mode 100644 index 0000000..6194955 --- /dev/null +++ b/skills/mdns-camera-discovery/SKILL.md @@ -0,0 +1,27 @@ +--- +name: mdns-camera-discovery +description: Implement and validate HomeKit camera discovery from DNS-SD mDNS announcements in Heimdall Agent. +--- + +# Heimdall mDNS camera discovery + +Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing discovery behavior. + +## Ownership and data flow + +- `Heimdall.Mdns/MdnsClient` owns UDP multicast and DNS-SD PTR/SRV/TXT/A parsing. Keep network operations cancellable and dispose sockets per operation. +- `HomeKitMdnsProbe` maps only categories 17 (camera) and 18 (doorbell) into Agent discovery records. +- `NetworkCameraScanner` is the Agent-side source of LAN probes. Preserve HomeKit metadata when its TCP scan has already found the same IP. Central persists and returns metadata; it must not probe the camera LAN. +- Resolve an accessory address from an A record attached to the instance or from the exact SRV target hostname. Never use another advertisement's arbitrary A record as a fallback. + +## Synthetic acceptance + +- Build synthetic DNS response packets with PTR `_hap._tcp.local` → instance, SRV instance → hostname/port, TXT `ci`, `sf`, `id`, `md`, and A hostname → address. Include an unrelated A record to verify strict SRV association. +- Verify camera and doorbell categories are kept, unrelated categories are filtered, `sf=0` maps to paired, and missing SRV-target A does not invent an address. +- Verify `HomeKitMdnsProbe` maps address/name/id/model/category/pairing/port into its Agent contract, and cancellation yields an empty result. +- Run the focused Agent tests and the full Agent test project after changes. +- The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists. + +## Disposable Compose + +Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index f8a5ad5..ad0d940 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -10,9 +10,11 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries. - Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port. - Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback. +- Central quota is configured with `RECORDING_STORAGE_QUOTA_MAX_BYTES` in Compose (application key `Recordings:StorageQuota:MaxBytes`, default 1 TiB). Options are validated on startup; a segment that would exceed the aggregate persisted recording bytes receives HTTP 507 and its uploaded object is removed. The PostgreSQL advisory transaction lock makes the aggregate check atomic across simultaneous Agent uploads; upload bytes finish before acquiring the short metadata lock. Give each upload attempt a unique object key below its recording ID so a racing idempotent retry cannot overwrite the winning segment; remove the losing attempt's object even when both use the same camera. - The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL. - Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance. -- Add PostgreSQL tests for migration, metadata/idempotency, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. +- Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. - For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. +- For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. -Current product gaps are audio/event-trigger capture, an explicit Central storage quota, and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. +Current product gaps are audio/event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md index 1f96f68..62de39e 100644 --- a/skills/vision-identity/SKILL.md +++ b/skills/vision-identity/SKILL.md @@ -1,33 +1,39 @@ --- name: vision-identity -description: Extend Heimdall's person, face-embedding, vehicle, and license-plate data paths without logging biometric data or shipping unapproved model weights. +description: Implement Heimdall's opt-in, self-hosted plate OCR and preserve the licensing/privacy gates for camera face and plate identity. --- -# Heimdall vision identity data +# Vision identity in Heimdall -## Current project behavior +Read `AGENTS.md` and FEAT-03/UI-02 in `todo.md`. Current API contract only supports a human-triggered OCR request with an operator-supplied JPEG/PNG plate crop. It does not infer plate boxes from video frames or recognize faces. -- `AnalysisJobPollingService` currently executes only `ObjectDetection`; do not describe the current Agent as performing face recognition or license-plate OCR. -- `KnownFace` is a manually registered vector record, not a face detector or recognition model. Inputs are limited to 4,096 finite float values, copied on construction, and the API body is capped at 256 KiB. Never log or include vector values in audit data. -- `LicensePlate` is a persisted observation record. Its text limit must match the PostgreSQL column (20 characters); confidence must be finite and in `[0,1]`. -- Face embeddings, plate text, and source images are sensitive. Preserve per-person deletion/cascade behavior, keep event camera authorization at API and application boundaries, and do not send frames or embeddings to external services. +## Plate OCR currently implemented -## Model review gate +- `PlateOcr:Enabled` defaults to false. Explicitly enable the on-prem Central option to offer OCR; the camera detail UI sends only the file the user selected. +- Central uses the system Tesseract executable and English LSTM data. Tesseract engine and the official `tessdata_best` model data declare Apache-2.0. Do not add other OCR or detection weights without reviewing their exact asset licenses and provenance. +- The controller requires a human principal with `Camera.Write`, camera scope, JPEG/PNG signature, configured byte limit (at most 512 KiB), and rate limits. OCR rejects malformed, oversized, or over-4-megapixel crops and times out after a bounded interval. +- OCR runs on the Heimdall Central host. The image is written to a random temporary path and deleted in `finally`; do not log the crop, extracted text, embedding, or raw image path. +- Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it deliberately does not persist `VehicleId`/`PersonId` links. Never treat OCR output as verified identity; a human confirmation/linking workflow is still missing. +- OCR observations remain unassigned and use the existing cleanup that purges unassigned plate rows after 30 days. The `LicensePlateDetected` event label and metadata have no equivalent retention in this change, so event retention/privacy review remains open before enabling this in production. -Before adding inference, record the exact model artifact URL/version, checksum, training-data terms, model-weight license, code/runtime license, regions/languages represented, preprocessing, hardware/runtime requirements, and an offline installation path. A repository code license alone does not establish the license of its pretrained weights. +## Face-model gate -Review findings as of 2026-11-04: +ONNX Runtime is already used by the Agent and is MIT licensed. A model runtime license does not grant rights to a particular model's weights or training data. InsightFace's model-zoo documentation restricts its distributed pretrained weights to non-commercial research. ONNX Model Zoo's ArcFace/UltraFace listing points to sourced models but does not establish one blanket weight/data license. Do not bundle SFace, ArcFace, YuNet, or plate-detector weights unless the exact asset and training-data rights are reviewed. An operator-provided model also needs a documented tensor/preprocessing contract, stable model ID stored with enrollments, explicit opt-in, deletion/retention semantics, and representative accuracy testing before face matches can create events. -- [InsightFace model-zoo license notice](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md) says its pretrained models are for non-commercial research; do not ship them for this product without separate permission. -- [FaceONNX model README](https://github.com/FaceONNX/FaceONNX.Models/blob/main/README.md) licenses the library as MIT but links models via Google Drive without specifying a separate model-weight license; treat weights as unresolved. -- [PaddleOCR license page](https://www.paddleocr.ai/v2.10.0/en/index.html) states Apache-2.0 for the project. It does not, by itself, establish rights for a particular license-plate model artifact; verify that artifact's own license and training data. -- [LdDl license-plate-recognition](https://github.com/LdDl/license_plate_recognition) declares Apache-2.0 for the repository and says its pretrained networks were trained on Russian plates. The repository does not separately establish weight rights or accuracy for Heimdall's target regions. +Official sources reviewed: -Do not download or bundle model files until their artifact-level rights and target-region accuracy are reviewed. Keep accuracy claims open until validated on an appropriately licensed, representative dataset and camera conditions. +- [Tesseract engine license and command-line formats](https://github.com/tesseract-ocr/tesseract) +- [Official `tessdata_best` license](https://github.com/tesseract-ocr/tessdata_best) +- [Official `tessdata` language-data license](https://github.com/tesseract-ocr/tessdata) +- [Official Tesseract data-file compatibility guidance](https://github.com/tesseract-ocr/tessdoc/blob/main/Data-Files.md) +- [ONNX Runtime repository license](https://github.com/microsoft/onnxruntime) +- [ONNX Model Zoo sourcing and model catalog](https://github.com/onnx/models/blob/main/README.md) +- [InsightFace model-zoo license statement](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md) ## Acceptance -1. Run Domain, Application, Infrastructure, and Web tests for changed layers; test EF translation/deletion behavior with PostgreSQL when persistence semantics change. -2. For a new model, test model verification/hash rejection, explicit opt-in, CPU fallback, and no outbound frame/embedding requests. Keep the exact artifact out of the repo unless its license and source are approved. -3. Exercise person and vehicle access through the authenticated API/UI, including deletion of the person and the documented retention behavior of linked event history and embeddings. -4. For behavior changes, run the disposable Compose acceptance from `skills/compose-disposable-recipe/SKILL.md`; keep generated data and credentials isolated and remove only that project. +1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test. +2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. +3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing. +4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. +5. This acceptance covers one clean synthetic crop and API persistence only. It does not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or event retention/privacy suitability. diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md index df5110e..27070c4 100644 --- a/skills/webrtc-live/SKILL.md +++ b/skills/webrtc-live/SKILL.md @@ -69,4 +69,4 @@ the Agent. Configure its assigned camera against the host loopback RTSP port. Do 6. Tear down only that Compose project with volumes/orphans, then verify its containers, volumes and network are gone. -Record LAN browser and external TURN runs independently. Current focused API/Web and Agent tests pass. Disposable Compose verified Central bootstrap/site creation, Agent registration, synthetic camera assignment, publish-session issuance and relay start, read ticket callback acceptance, forged-ticket denial, unknown-camera denial, and teardown with no remaining project containers, volumes or networks. A deliberately invalid SDP reached MediaMTX and returned 400; a browser-decoded frame and API-driven disable stop were not verified. Physical camera, LAN, external TURN and real SDP/frame playback remain unvalidated; keep FEAT-01 open until these acceptance gaps are closed. +Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and the Agent relay test (1/1) pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Physical camera, LAN and external TURN are unvalidated; audio/PTZ remain out of scope, so keep FEAT-01 open. diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs index 260af86..4359bec 100644 --- a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs +++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs @@ -265,7 +265,7 @@ public NetworkCameraScanner( /// are kept; the HomeKit* fields of the device are filled for the Central /// ClassifyAgentDevice HomeKit path. ///
- private async Task> DiscoverHomeKitAsync(CancellationToken ct) + internal async Task> DiscoverHomeKitAsync(CancellationToken ct) { var devices = new List(); try diff --git a/src/Heimdall.Application/Common/IRecordingQuotaGuard.cs b/src/Heimdall.Application/Common/IRecordingQuotaGuard.cs new file mode 100644 index 0000000..416f98b --- /dev/null +++ b/src/Heimdall.Application/Common/IRecordingQuotaGuard.cs @@ -0,0 +1,14 @@ +namespace Heimdall.Application.Common; + +/// Serializes recording usage checks across cameras and exposes the validated Central quota. +public interface IRecordingQuotaGuard +{ + long MaxStorageBytes { get; } + Task AcquireAsync(CancellationToken ct = default); +} + +/// A short-lived database transaction holding the global recording quota lock. +public interface IRecordingQuotaLease : IAsyncDisposable +{ + Task CommitAsync(CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs index afc8fc5..d6a95c8 100644 --- a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs +++ b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs @@ -4,6 +4,7 @@ using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using MediatR; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; namespace Heimdall.Application.Recordings.Commands.UploadRecording; @@ -18,7 +19,10 @@ public sealed record UploadRecordingCommand( public sealed class UploadRecordingHandler( IApplicationDbContext db, - IRecordingStorage storage) : IRequestHandler> + IRecordingStorage storage, + IRecordingQuotaGuard quota, + IStorageObjectDeletion objectDeletion, + ILogger logger) : IRequestHandler> { public async Task> Handle(UploadRecordingCommand request, CancellationToken ct) { @@ -29,9 +33,9 @@ public sealed class UploadRecordingHandler( var camera = await db.Cameras.AsNoTracking() .Where(c => c.Id == request.CameraId && !c.IsDeleted) - .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId }) + .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled }) .SingleOrDefaultAsync(ct).ConfigureAwait(false); - if (camera?.AgentId != request.AgentId) + if (camera?.AgentId != request.AgentId || !camera.RecordingEnabled) return ServiceResult.NotFound("Camera not found"); var existing = await db.Recordings.AsNoTracking() @@ -45,23 +49,100 @@ public sealed class UploadRecordingHandler( var timestamp = CameraEvent.NormalizeOccurredAt(request.Timestamp); var location = storage.CaptureCurrentLocation(); - var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}.mp4"; - if (request.Content.CanSeek) request.Content.Position = 0; - await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false); + // Each attempt gets its own key so a racing retry cannot overwrite the winner's object + // before the transaction discovers its already-persisted metadata row. + var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}/{Guid.NewGuid():N}.mp4"; - var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds, - key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId); - db.Recordings.Add(recording); - await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + var shouldDeleteObject = false; + var commitAttempted = false; + try + { + if (request.Content.CanSeek) request.Content.Position = 0; + await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false); - var end = timestamp.AddSeconds(request.DurationSeconds); - await db.CameraEvents - .Where(e => e.CameraId == request.CameraId && e.RecordingId == null && e.OccurredAt >= timestamp && e.OccurredAt < end) - .ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct) - .ConfigureAwait(false); + ServiceResult result; + await using (var quotaLease = await quota.AcquireAsync(ct).ConfigureAwait(false)) + { + // Recheck under the quota lock to keep duplicate retries safe when uploads race. + existing = await db.Recordings.AsNoTracking() + .Where(r => r.Id == request.RecordingId) + .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (existing is not null) + { + // The uploaded key is unique to this attempt, so it cannot be the + // already-persisted object's key and is safe to remove in either case. + shouldDeleteObject = true; + result = existing.CameraId == request.CameraId + ? ServiceResult.Success(Map(existing.Id, existing.CameraId, + existing.Timestamp, existing.DurationSeconds, existing.SizeBytes)) + : ServiceResult.Conflict("Recording identifier already belongs to another camera"); + commitAttempted = true; + await quotaLease.CommitAsync(ct).ConfigureAwait(false); + } + else + { + var usedBytes = await db.Recordings.AsNoTracking() + .SumAsync(r => (long?)r.SizeBytes, ct).ConfigureAwait(false) ?? 0; + var overQuota = request.SizeBytes > quota.MaxStorageBytes || + usedBytes > quota.MaxStorageBytes - request.SizeBytes; + if (overQuota) + { + shouldDeleteObject = true; + result = ServiceResult.Failure( + "Central recording storage quota exceeded; segment was not retained", 507); + commitAttempted = true; + await quotaLease.CommitAsync(ct).ConfigureAwait(false); + } + else + { + var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds, + key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId); + db.Recordings.Add(recording); + await db.SaveChangesAsync(ct).ConfigureAwait(false); - return ServiceResult.Success(Map(recording.Id, recording.CameraId, - recording.Timestamp, recording.DurationSeconds, recording.SizeBytes)); + var end = timestamp.AddSeconds(request.DurationSeconds); + await db.CameraEvents + .Where(e => e.CameraId == request.CameraId && e.RecordingId == null && + e.OccurredAt >= timestamp && e.OccurredAt < end) + .ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct) + .ConfigureAwait(false); + + commitAttempted = true; + await quotaLease.CommitAsync(ct).ConfigureAwait(false); + result = ServiceResult.Success(Map(recording.Id, recording.CameraId, + recording.Timestamp, recording.DurationSeconds, recording.SizeBytes)); + } + } + } + + if (shouldDeleteObject) + await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, ct).ConfigureAwait(false); + return result; + } + catch + { + // Once commit starts its outcome can be ambiguous; leave this attempt's unique object + // for the retry/orphan sweep instead of risking deletion after a successful DB commit. + if (!commitAttempted) + await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, CancellationToken.None) + .ConfigureAwait(false); + throw; + } + } + + private async Task TryDeleteUploadedObjectAsync(string key, StorageLocation location, Guid recordingId, + CancellationToken ct) + { + try + { + await objectDeletion.DeleteBatchAsync([key], location, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + logger.LogWarning("Could not clean up an unretained recording object {RecordingId} (error type {ErrorType})", + recordingId, ex.GetType().Name); + } } private static RecordingDto Map(Guid id, Guid cameraId, DateTime timestamp, double duration, long size) => diff --git a/src/Heimdall.Application/Services/ILicensePlateOcr.cs b/src/Heimdall.Application/Services/ILicensePlateOcr.cs new file mode 100644 index 0000000..d1247d4 --- /dev/null +++ b/src/Heimdall.Application/Services/ILicensePlateOcr.cs @@ -0,0 +1,18 @@ +namespace Heimdall.Application.Services; + +public sealed record PlateOcrResult(string Text, double Confidence); + +/// Runs self-hosted OCR over a user-supplied plate crop. +public interface ILicensePlateOcr +{ + Task RecognizeAsync(ReadOnlyMemory image, CancellationToken ct); +} + +public sealed record LicensePlateRecognitionResponse(Guid PlateId, Guid EventId, string PlateText, + double Confidence, Guid? SuggestedVehicleId, Guid? SuggestedPersonId); + +public interface ILicensePlateRecognitionService +{ + Task> RecognizeAsync( + Guid cameraId, ReadOnlyMemory image, CancellationToken ct); +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 6973e32..7f6b219 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -45,6 +45,12 @@ public static class DependencyInjection services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); + services.AddOptions() + .Bind(configuration.GetSection(PlateOcrOptions.SectionName)) + .Validate(options => options.IsValid(), "Plate OCR options are invalid") + .ValidateOnStart(); + services.AddSingleton(); + services.AddScoped(); // Stockage (spec Phase 8) — provider résolu depuis les settings DB // (storage.provider = Local | S3), factory scoped (lit la config à @@ -52,7 +58,6 @@ public static class DependencyInjection services.AddSingleton(); services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); - services.AddScoped(); // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() diff --git a/src/Heimdall.Infrastructure/Services/LicensePlateRecognitionService.cs b/src/Heimdall.Infrastructure/Services/LicensePlateRecognitionService.cs new file mode 100644 index 0000000..dc7e5c9 --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/LicensePlateRecognitionService.cs @@ -0,0 +1,50 @@ +using System.Text.Json; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Services; + +public sealed class LicensePlateRecognitionService( + IDbContextFactory dbFactory, + ILicensePlateOcr ocr) : ILicensePlateRecognitionService +{ + public async Task> RecognizeAsync( + Guid cameraId, ReadOnlyMemory image, CancellationToken ct) + { + var result = await ocr.RecognizeAsync(image, ct).ConfigureAwait(false); + if (result is null) return ServiceResult.Failure("OCR could not read this plate crop", 422); + var plateText = new string(result.Text.Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray()) + .ToUpperInvariant(); + if (plateText.Length is < 3 or > LicensePlate.MaxPlateTextLength) + return ServiceResult.Failure("OCR output is not a valid plate candidate", 422); + + await using var db = await dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false); + var camera = await db.Cameras.AsNoTracking() + .Where(c => c.Id == cameraId && !c.IsDeleted) + .Select(c => new { c.Id, c.SiteId }) + .FirstOrDefaultAsync(ct).ConfigureAwait(false); + if (camera is null) return ServiceResult.NotFound("Camera not found"); + + var normalized = plateText.Replace("-", string.Empty); + var vehicles = await db.Vehicles.AsNoTracking() + .Where(v => v.LicensePlate != null && v.LicensePlate.Replace("-", "") == normalized) + .OrderBy(v => v.Id) + .Take(2) + .Select(v => new { v.Id, v.PersonId }) + .ToListAsync(ct).ConfigureAwait(false); + // Suggest only. OCR output is not proof of identity: a human must verify it before linking. + var vehicle = vehicles.Count == 1 ? vehicles[0] : null; + var observation = new LicensePlate(plateText, confidence: result.Confidence); + var ev = new CameraEvent(cameraId, EventType.LicensePlateDetected, result.Confidence); + ev.SetMetadata(plateText, JsonSerializer.Serialize(new { source = "local-opt-in-ocr", plateId = observation.Id })); + db.LicensePlates.Add(observation); + db.CameraEvents.Add(ev); + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + return ServiceResult.Success( + new(observation.Id, ev.Id, plateText, result.Confidence, vehicle?.Id, vehicle?.PersonId)); + } +} diff --git a/src/Heimdall.Infrastructure/Services/TesseractPlateOcr.cs b/src/Heimdall.Infrastructure/Services/TesseractPlateOcr.cs new file mode 100644 index 0000000..d62f91f --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/TesseractPlateOcr.cs @@ -0,0 +1,150 @@ +using System.Diagnostics; +using System.Globalization; +using Microsoft.Extensions.Options; + +namespace Heimdall.Infrastructure.Services; + +public sealed class PlateOcrOptions +{ + public const string SectionName = "PlateOcr"; + public bool Enabled { get; set; } + public string ExecutablePath { get; set; } = "/usr/bin/tesseract"; + public int MaxImageBytes { get; set; } = 512 * 1024; + public int TimeoutSeconds { get; set; } = 10; + + public bool IsValid() => !Enabled || + (!string.IsNullOrWhiteSpace(ExecutablePath) && MaxImageBytes is >= 1024 and <= 512 * 1024 && + TimeoutSeconds is >= 1 and <= 60); +} + +/// Invokes local Tesseract against a temporary, bounded image crop. +public sealed class TesseractPlateOcr(IOptionsMonitor options) : Application.Services.ILicensePlateOcr +{ + public async Task RecognizeAsync(ReadOnlyMemory image, CancellationToken ct) + { + var settings = options.CurrentValue; + if (!settings.Enabled || !IsSafeImage(image.Span, settings.MaxImageBytes)) + return null; + + var tempFile = Path.Combine(Path.GetTempPath(), $"heimdall-plate-{Guid.NewGuid():N}.img"); + try + { + var fileOptions = new FileStreamOptions + { + Mode = FileMode.CreateNew, + Access = FileAccess.Write, + Share = FileShare.None, + BufferSize = 4096 + }; + if (!OperatingSystem.IsWindows()) + fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + await using (var output = new FileStream(tempFile, fileOptions)) + await output.WriteAsync(image, ct).ConfigureAwait(false); + var start = new ProcessStartInfo(settings.ExecutablePath) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + start.ArgumentList.Add(tempFile); + start.ArgumentList.Add("stdout"); + start.ArgumentList.Add("--oem"); start.ArgumentList.Add("1"); + start.ArgumentList.Add("--psm"); start.ArgumentList.Add("7"); + start.ArgumentList.Add("-l"); start.ArgumentList.Add("eng"); + start.ArgumentList.Add("tsv"); + start.ArgumentList.Add("-c"); start.ArgumentList.Add("tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"); + + using var process = Process.Start(start); + if (process is null) return null; + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(settings.TimeoutSeconds)); + try + { + var stdoutTask = process.StandardOutput.ReadToEndAsync(timeout.Token); + var stderrTask = process.StandardError.ReadToEndAsync(timeout.Token); + await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(timeout.Token)).ConfigureAwait(false); + var stdout = await stdoutTask.ConfigureAwait(false); + if (process.ExitCode != 0 || stdout.Length > 32_768) return null; + return ParseTsv(stdout); + } + catch (OperationCanceledException) + { + try { process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { } + if (ct.IsCancellationRequested) throw; + return null; + } + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or IOException or + UnauthorizedAccessException or InvalidOperationException) + { + return null; + } + finally + { + try { File.Delete(tempFile); } catch (IOException) { } + } + } + + public static Application.Services.PlateOcrResult? ParseTsv(string tsv) + { + var text = new System.Text.StringBuilder(); + var confidenceSum = 0d; + var words = 0; + foreach (var line in tsv.Split('\n').Skip(1)) + { + var fields = line.TrimEnd('\r').Split('\t'); + if (fields.Length < 12 || !double.TryParse(fields[10], NumberStyles.Float, + CultureInfo.InvariantCulture, out var confidence) || !double.IsFinite(confidence) || confidence < 0 || string.IsNullOrWhiteSpace(fields[11])) + continue; + var token = new string(fields[11].Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray()); + if (token.Length == 0) continue; + if (text.Length > 0) text.Append(' '); + text.Append(token.ToUpperInvariant()); + confidenceSum += Math.Clamp(confidence / 100d, 0, 1); + words++; + } + return words == 0 ? null : new Application.Services.PlateOcrResult(text.ToString(), confidenceSum / words); + } + + public static bool IsSafeImage(ReadOnlySpan image, int maxBytes = 512 * 1024) => + image.Length is >= 16 && image.Length <= maxBytes && + PlateImageHeader.TryGetDimensions(image, out var width, out var height) && + width is >= 32 and <= 4096 && height is >= 16 and <= 4096 && (long)width * height <= 4_000_000; +} + +internal static class PlateImageHeader +{ + public static bool TryGetDimensions(ReadOnlySpan data, out int width, out int height) + { + width = height = 0; + if (data.Length >= 24 && data[..8].SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 })) + { + width = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(16, 4)); + height = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(20, 4)); + return width > 0 && height > 0; + } + + if (data.Length < 4 || data[0] != 0xff || data[1] != 0xd8) return false; + var offset = 2; + while (offset + 4 <= data.Length) + { + if (data[offset++] != 0xff) return false; + while (offset < data.Length && data[offset] == 0xff) offset++; + if (offset >= data.Length) return false; + var marker = data[offset++]; + if (marker is 0xd8 or 0xd9 or 0x01 || marker is >= 0xd0 and <= 0xd7) continue; + var segmentLength = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2)); + if (segmentLength < 2 || offset + segmentLength > data.Length) return false; + if (marker is >= 0xc0 and <= 0xc3 or >= 0xc5 and <= 0xc7 or >= 0xc9 and <= 0xcb or >= 0xcd and <= 0xcf) + { + if (segmentLength < 7) return false; + height = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 3, 2)); + width = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 5, 2)); + return width > 0 && height > 0; + } + offset += segmentLength; + } + return false; + } +} diff --git a/src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs b/src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs new file mode 100644 index 0000000..7e9cb03 --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs @@ -0,0 +1,43 @@ +using System.Data; +using Heimdall.Application.Common; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Options; + +namespace Heimdall.Infrastructure.Storage; + +/// Uses one PostgreSQL transaction advisory lock to make the global quota check atomic. +public sealed class RecordingQuotaGuard( + AppDbContext db, + IOptions options) : IRecordingQuotaGuard +{ + private const long QuotaLockKey = 0x4845494D44525155; + + public long MaxStorageBytes => options.Value.MaxBytes; + + public async Task AcquireAsync(CancellationToken ct = default) + { + var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct) + .ConfigureAwait(false); + try + { + // EF Core exception: PostgreSQL transaction advisory locks have no portable LINQ equivalent. + // The lock serializes only the short metadata/quota check, after object upload has completed. + await db.Database.ExecuteSqlInterpolatedAsync( + $"SELECT pg_advisory_xact_lock({QuotaLockKey})", ct).ConfigureAwait(false); + return new TransactionLease(transaction); + } + catch + { + await transaction.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + private sealed class TransactionLease(IDbContextTransaction transaction) : IRecordingQuotaLease + { + public Task CommitAsync(CancellationToken ct = default) => transaction.CommitAsync(ct); + public ValueTask DisposeAsync() => transaction.DisposeAsync(); + } +} diff --git a/src/Heimdall.Infrastructure/Storage/RecordingStorageQuotaOptions.cs b/src/Heimdall.Infrastructure/Storage/RecordingStorageQuotaOptions.cs new file mode 100644 index 0000000..db2d316 --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/RecordingStorageQuotaOptions.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace Heimdall.Infrastructure.Storage; + +/// Central-wide cap for bytes stored as camera recordings. +public sealed class RecordingStorageQuotaOptions +{ + public const string SectionName = "Recordings:StorageQuota"; + + /// Maximum persisted recording bytes; defaults to 1 TiB. + [Range(1, long.MaxValue)] + public long MaxBytes { get; set; } = 1L << 40; +} diff --git a/src/Heimdall.Mdns/AssemblyInfo.cs b/src/Heimdall.Mdns/AssemblyInfo.cs new file mode 100644 index 0000000..3770251 --- /dev/null +++ b/src/Heimdall.Mdns/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Heimdall.Agent.Tests")] diff --git a/src/Heimdall.Mdns/MdnsClient.cs b/src/Heimdall.Mdns/MdnsClient.cs index e2572ab..07f743d 100644 --- a/src/Heimdall.Mdns/MdnsClient.cs +++ b/src/Heimdall.Mdns/MdnsClient.cs @@ -289,6 +289,21 @@ public sealed class MdnsClient : IMdnsClient, IDisposable } } + internal static IReadOnlyList ParseMulticastResponses(IEnumerable packets) + { + ArgumentNullException.ThrowIfNull(packets); + var replies = new List(); + foreach (var packet in packets) + { + if (packet is not null) + replies.AddRange(ParsePacket(packet)); + } + + return BuildDevices(replies) + .Where(device => device.HomeKitInfo?.Category is 17 or 18) + .ToArray(); + } + private static List ParsePacket(byte[] data) { var replies = new List(); @@ -453,7 +468,6 @@ public sealed class MdnsClient : IMdnsClient, IDisposable // target host, then any A record seen (best effort). var ip = info.Ips.FirstOrDefault() ?? (info.SrvTarget is not null && addressByHost.TryGetValue(info.SrvTarget, out var srvIp) ? srvIp : null) - ?? addressByHost.Values.FirstOrDefault() ?? ""; if (string.IsNullOrEmpty(ip) || !seenIps.Add(ip)) diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 1c63c88..0473a1b 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -5,6 +5,7 @@ @inject ISnackbar Snackbar @inject NavigationManager Nav @inject UiText Text +@using Microsoft.AspNetCore.Components.Forms @inject UiLanguageService Language @inject IJSRuntime JS @implements IAsyncDisposable @@ -199,6 +200,20 @@ else @Text["CameraDetail_NoRecordings"] } + + @Text["CameraDetail_PlateOcrTitle"] + @Text["CameraDetail_PlateOcrPrivacy"] + + @if (_recognizingPlate) + { + + } + @if (!string.IsNullOrEmpty(_plateOcrMessage)) + { + @_plateOcrMessage + } + + @* ─── Mini-timeline : événements récents ─── *@ @Text["CameraDetail_RecentEvents"] @@ -285,6 +300,9 @@ else private bool _togglingStatus; private bool _showRtsp; private bool _confirmDeleteShow; + private bool _recognizingPlate; + private bool _plateOcrSuccess; + private string? _plateOcrMessage; private List? _events; private List _recordings = []; @@ -350,6 +368,33 @@ else finally { _eventsLoading = false; } } + private async Task RecognizePlateCropAsync(InputFileChangeEventArgs args) + { + var file = args.File; + if (file.Size is < 16 or > 512 * 1024 || file.ContentType is not ("image/jpeg" or "image/png")) + { + _plateOcrSuccess = false; + _plateOcrMessage = Text["CameraDetail_PlateOcrInvalid"]; + return; + } + + _recognizingPlate = true; + _plateOcrMessage = null; + try + { + await using var stream = file.OpenReadStream(512 * 1024); + var response = await Api.RecognizePlateCropAsync(Id, stream, file.ContentType, file.Name); + _plateOcrSuccess = response.Succeeded; + _plateOcrMessage = response.Succeeded && response.Data is not null + ? string.Format(Language.Culture, Text["CameraDetail_PlateOcrResult"], response.Data.PlateText, + (response.Data.Confidence * 100).ToString("0", Language.Culture)) + : response.ErrorMessage ?? Text["CameraDetail_OperationFailed"]; + if (response.Succeeded) await LoadEventsAsync(); + } + catch { _plateOcrSuccess = false; _plateOcrMessage = Text["CameraDetail_OperationFailed"]; } + finally { _recognizingPlate = false; } + } + private async Task LoadRecordingsAsync() { _recordingsLoading = true; @@ -531,6 +576,7 @@ else "PersonDetected" => Text["CameraDetail_EventPerson"], "VehicleDetected" => Text["CameraDetail_EventVehicle"], "FaceRecognized" => Text["CameraDetail_EventFace"], + "LicensePlateDetected" => Text["LicensePlateDetected"], "CameraOffline" => Text["CameraDetail_StatusOffline"], _ => type }; @@ -541,6 +587,7 @@ else "PersonDetected" => Color.Error, "VehicleDetected" => Color.Info, "FaceRecognized" => Color.Success, + "LicensePlateDetected" => Color.Info, _ => Color.Default }; diff --git a/src/Heimdall.Web/Components/Pages/EventsPage.razor b/src/Heimdall.Web/Components/Pages/EventsPage.razor index e525378..0feeb60 100644 --- a/src/Heimdall.Web/Components/Pages/EventsPage.razor +++ b/src/Heimdall.Web/Components/Pages/EventsPage.razor @@ -242,6 +242,7 @@ else "PersonDetected" => Text["EventsPage_Person"], "VehicleDetected" => Text["EventsPage_Vehicle"], "FaceRecognized" => Text["EventsPage_Face"], + "LicensePlateDetected" => Text["LicensePlateDetected"], "CameraOffline" => Text["EventsPage_Offline"], _ => type }; @@ -252,6 +253,7 @@ else "PersonDetected" => Color.Error, "VehicleDetected" => Color.Info, "FaceRecognized" => Color.Success, + "LicensePlateDetected" => Color.Info, _ => Color.Default }; diff --git a/src/Heimdall.Web/Controllers/PlateRecognitionController.cs b/src/Heimdall.Web/Controllers/PlateRecognitionController.cs new file mode 100644 index 0000000..2702e81 --- /dev/null +++ b/src/Heimdall.Web/Controllers/PlateRecognitionController.cs @@ -0,0 +1,48 @@ +using Heimdall.Application.Services; +using Heimdall.Api.Security; +using Heimdall.Infrastructure.Security; +using Heimdall.Infrastructure.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api/cameras/{cameraId:guid}/plate-recognition")] +[EnableRateLimiting("Api")] +public sealed class PlateRecognitionController( + ResourceAccess access, + ILicensePlateRecognitionService recognition, + IOptionsMonitor options) : ControllerBase +{ + private const int MaxCropBytes = 512 * 1024; + + /// Processes a user-selected plate crop locally; image bytes are discarded after OCR. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] + [HttpPost] + [RequestSizeLimit(MaxCropBytes + 16 * 1024)] + [Consumes("multipart/form-data")] + public async Task Recognize(Guid cameraId, IFormFile? image, CancellationToken ct) + { + if (!options.CurrentValue.Enabled) return StatusCode(503, new { error = "Local plate OCR is disabled" }); + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + if (image is null || image.Length is < 16 or > MaxCropBytes || image.Length > options.CurrentValue.MaxImageBytes || + image.ContentType is not ("image/jpeg" or "image/png")) + return BadRequest(new { error = "Provide a JPEG or PNG plate crop up to 512 KiB" }); + + await using var input = image.OpenReadStream(); + using var buffer = new MemoryStream((int)image.Length); + await input.CopyToAsync(buffer, ct); + var bytes = buffer.ToArray(); + var png = bytes.AsSpan().StartsWith(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }); + var jpeg = bytes.AsSpan().StartsWith(new byte[] { 255, 216, 255 }); + if (!png && !jpeg) return BadRequest(new { error = "Image content does not match JPEG or PNG" }); + + var result = await recognition.RecognizeAsync(cameraId, bytes, ct); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 422, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 5e00620..557b133 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -4109,4 +4109,8 @@ Watch live Stop live Live view is unavailable. Check the media service and camera access. + Local plate reading (manual action) + Select a JPEG/PNG crop of the plate. The image is processed on this Heimdall server and deleted afterward; only the plate observation and history event are stored. Enable the feature in configuration first. + Select a JPEG or PNG crop no larger than 512 KiB. + Plate {0} recognized with {1}% confidence; an event was added to history. diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 7773b7a..456a691 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -4109,4 +4109,8 @@ Voir en direct Arrêter le direct Le direct est indisponible. Vérifiez le service média et les droits caméra. + Lecture de plaque locale (action manuelle) + Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration. + Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum. + Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique. diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index a2306e9..0f31954 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -4109,4 +4109,8 @@ Watch live Stop live Live view is unavailable. Check the media service and camera access. + Lecture de plaque locale (action manuelle) + Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration. + Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum. + Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique. diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 0542169..a8811c9 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -3,6 +3,7 @@ using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; using Heimdall.Application.DTOs; +using Heimdall.Application.Services; namespace Heimdall.Web.Services; @@ -514,6 +515,22 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync($"api/cameras/{id}", Json); } + public async Task> RecognizePlateCropAsync( + Guid cameraId, Stream image, string contentType, string fileName, CancellationToken ct = default) + { + using var content = new MultipartFormDataContent(); + using var imageContent = new StreamContent(image); + imageContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + content.Add(imageContent, "image", Path.GetFileName(fileName)); + using var response = await CreateClient().PostAsync($"api/cameras/{cameraId:D}/plate-recognition", content, ct); + if (!response.IsSuccessStatusCode) + return ApiResult.Failure(await ReadErrorMessageAsync(response)); + var result = await response.Content.ReadFromJsonAsync(Json, ct); + return result is null + ? ApiResult.Failure(InvalidServerResponse) + : ApiResult.Success(result); + } + public async Task?> GetCameraRecordingsAsync(Guid id, int page = 1, int pageSize = 20) { var client = CreateClient(); diff --git a/src/Heimdall.Web/wwwroot/js/live-view.js b/src/Heimdall.Web/wwwroot/js/live-view.js index f297a07..b274b26 100644 --- a/src/Heimdall.Web/wwwroot/js/live-view.js +++ b/src/Heimdall.Web/wwwroot/js/live-view.js @@ -36,8 +36,8 @@ export async function stop(cameraId) { const s = active.get(cameraId); if (!s) return; active.delete(cameraId); - s.pc.close(); if (s.resource) { try { await fetch(s.resource, { method: "DELETE", headers: { Authorization: `Bearer ${s.token}` } }); } catch { } } + s.pc.close(); try { await fetch(`/api/live-media/cameras/${cameraId}/session/${s.sessionId}`, { method: "DELETE", credentials: "same-origin" }); } catch { } const v = document.querySelector(`[data-live-camera="${cameraId}"]`); if (v) v.srcObject = null; diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs index 8e65235..dadca78 100644 --- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs @@ -485,21 +485,63 @@ public class ConfigReceiverServiceTests { var cameraId = Guid.NewGuid(); var settings = new Dictionary { [$"camera.{cameraId}.enabled"] = "true" }; - var handler = new RetryingCameraAckHandler(settings); + var expectedVersion = CameraConfigVersion.Compute(settings); + var configFetches = 0; + var ackAttempts = 0; + var persistedAcks = 0; + var acknowledgedVersions = new List(); + var builder = WebApplication.CreateBuilder(); + var fixturePort = int.TryParse(Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_PORT"), out var configuredPort) && + configuredPort is > 0 and <= 65535 ? configuredPort : 0; + var fixtureBindHost = Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_BIND_HOST") ?? "127.0.0.1"; + var fixtureApiKey = Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_API_KEY") ?? "fixture-key"; + builder.WebHost.UseUrls($"http://{fixtureBindHost}:{fixturePort}"); + builder.Logging.ClearProviders(); + await using var central = builder.Build(); + central.MapGet("/api/settings/agent/{id:guid}", (HttpContext context) => + { + Interlocked.Increment(ref configFetches); + if (!string.Equals(context.Request.Headers["X-API-Key"], fixtureApiKey, StringComparison.Ordinal)) + return Results.Unauthorized(); + context.Response.Headers["X-Camera-Config-Version"] = expectedVersion; + return Results.Json(settings); + }); + central.MapPost("/api/settings/agent/{id:guid}/camera-config-ack", async (HttpRequest request) => + { + Interlocked.Increment(ref ackAttempts); + if (!string.Equals(request.Headers["X-API-Key"], fixtureApiKey, StringComparison.Ordinal)) + return Results.Unauthorized(); + var ack = await request.ReadFromJsonAsync(); + if (ack is null || !string.Equals(ack.Version, expectedVersion, StringComparison.Ordinal)) + return Results.BadRequest(); + acknowledgedVersions.Add(ack.Version); + if (ackAttempts == 1) return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); + Interlocked.Increment(ref persistedAcks); + return Results.NoContent(); + }); + await central.StartAsync(); + var factory = Substitute.For(); - factory.CreateClient("Central").Returns(_ => new HttpClient(handler, disposeHandler: false)); + factory.CreateClient("Central").Returns(_ => new HttpClient()); var cameraStore = new CameraConfigStore(); - var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "fixture-key" }; - using var service = CreateService(state, httpFactory: factory, cameraStore: cameraStore); + var configurationApplications = 0; + cameraStore.Changed += (_, _) => Interlocked.Increment(ref configurationApplications); + var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = fixtureApiKey }; + using var service = CreateService(state, httpFactory: factory, cameraStore: cameraStore, + centralUrl: fixturePort == 0 ? central.Urls.Single() : $"http://127.0.0.1:{fixturePort}"); var fetch = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync", BindingFlags.NonPublic | BindingFlags.Instance); fetch.ShouldNotBeNull(); await (Task)fetch.Invoke(service, [CancellationToken.None])!; - handler.AcknowledgementAttempts.ShouldBe(2); + configFetches.ShouldBe(1); + ackAttempts.ShouldBe(2); + persistedAcks.ShouldBe(1); + acknowledgedVersions.ShouldBe([expectedVersion, expectedVersion]); + configurationApplications.ShouldBe(1); cameraStore.Cameras.ShouldHaveSingleItem().CameraId.ShouldBe(cameraId); - cameraStore.CurrentVersion.ShouldBe(CameraConfigVersion.Compute(settings)); + cameraStore.CurrentVersion.ShouldBe(expectedVersion); } [Fact] @@ -557,31 +599,7 @@ public class ConfigReceiverServiceTests } } - private sealed class RetryingCameraAckHandler : HttpMessageHandler - { - private readonly IReadOnlyDictionary _settings; - private int _acknowledgementAttempts; - - public RetryingCameraAckHandler(IReadOnlyDictionary settings) => _settings = settings; - public int AcknowledgementAttempts => Volatile.Read(ref _acknowledgementAttempts); - - protected override Task SendAsync(HttpRequestMessage request, - CancellationToken cancellationToken) - { - if (request.Method == HttpMethod.Post) - { - var attempt = Interlocked.Increment(ref _acknowledgementAttempts); - return Task.FromResult(new HttpResponseMessage(attempt == 1 - ? System.Net.HttpStatusCode.ServiceUnavailable - : System.Net.HttpStatusCode.NoContent)); - } - - var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) - { Content = JsonContent.Create(_settings) }; - response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(_settings)); - return Task.FromResult(response); - } - } + private sealed record CameraConfigAckRequest(string Version); /// Captures formatted log messages for assertions (in-memory, no sinks). private sealed class ListLoggerProvider : ILoggerProvider diff --git a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs index 63b3db8..1834f3d 100644 --- a/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs +++ b/tests/Heimdall.Agent.Tests/HomeKitMdnsProbeTests.cs @@ -1,6 +1,11 @@ using System.Text; +using System.Net; using Heimdall.Agent.Services; +using Heimdall.Application.DTOs; +using Heimdall.Mdns; using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Microsoft.Extensions.Logging; using Shouldly; namespace Heimdall.Agent.Tests; @@ -35,4 +40,159 @@ public class HomeKitMdnsProbeTests var probe = new HomeKitMdnsProbe(NullLogger.Instance); probe.ShouldNotBeNull(); } -} \ No newline at end of file + + [Fact] + public async Task DiscoverAsync_MapsCameraAnnouncementIntoAgentDevice() + { + var mdns = Substitute.For(); + mdns.DiscoverMulticastAsync(Arg.Any(), Arg.Any()) + .Returns([new MdnsDiscoveredDevice + { + Address = IPAddress.Parse("192.0.2.40"), + InstanceName = "Front Door._hap._tcp.local", + Port = 51926, + HomeKitInfo = new HomeKitDeviceInfo + { + Name = "Front Door", DeviceId = "AA:BB:CC:DD:EE:FF", Model = "TestCam", + Category = 18, IsPaired = true, Port = 51926 + } + }]); + + var devices = await new HomeKitMdnsProbe(mdns, NullLogger.Instance) + .DiscoverAsync(); + + devices.ShouldHaveSingleItem().ShouldBe(new HomeKitDevice( + "192.0.2.40", "Front Door", "AA:BB:CC:DD:EE:FF", "TestCam", 18, true, 51926)); + await mdns.Received(1).DiscoverMulticastAsync( + Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task DiscoverAsync_Canceled_ReturnsEmpty() + { + var mdns = Substitute.For(); + mdns.DiscoverMulticastAsync(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new OperationCanceledException()); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + (await new HomeKitMdnsProbe(mdns, NullLogger.Instance) + .DiscoverAsync(cts.Token)).ShouldBeEmpty(); + } + + [Fact] + public async Task NetworkCameraScanner_MapsHomeKitDiscoveryIntoCentralPayloadShape() + { + var mdns = Substitute.For(); + mdns.DiscoverMulticastAsync(Arg.Any(), Arg.Any()) + .Returns([new MdnsDiscoveredDevice + { + Address = IPAddress.Parse("192.0.2.41"), + InstanceName = "Garden._hap._tcp.local", + Port = 51927, + HomeKitInfo = new HomeKitDeviceInfo + { + Name = "Garden", DeviceId = "AA:BB:CC:DD:EE:11", Model = "Doorbell", + Category = 18, IsPaired = false, Port = 51927 + } + }]); + var probe = new HomeKitMdnsProbe(mdns, NullLogger.Instance); + var scanner = new NetworkCameraScanner(NullLogger.Instance, + NullLoggerFactory.Instance, probe); + + var result = await scanner.DiscoverHomeKitAsync(CancellationToken.None); + + var discovered = result.ShouldHaveSingleItem(); + discovered.Ip.ShouldBe("192.0.2.41"); + discovered.OpenPorts.ShouldBe([51927]); + discovered.Vendor.ShouldBe("Apple"); + discovered.HomeKitName.ShouldBe("Garden"); + discovered.HomeKitDeviceId.ShouldBe("AA:BB:CC:DD:EE:11"); + discovered.HomeKitModel.ShouldBe("Doorbell"); + discovered.HomeKitCategory.ShouldBe(18); + discovered.HomeKitIsPaired.ShouldBe(false); + discovered.HomeKitPort.ShouldBe(51927); + } + + [Fact] + public void ParseMulticastResponses_ResolvesSrvHostAndNeverBorrowsAnotherHostAddress() + { + var packet = BuildAnnouncement( + unrelatedHost: "other.local", unrelatedIp: "192.0.2.99", + instance: "Porch._hap._tcp.local", target: "porch.local", ip: "192.0.2.18"); + + var camera = MdnsClient.ParseMulticastResponses([packet]).ShouldHaveSingleItem(); + + camera.Address.ShouldBe(IPAddress.Parse("192.0.2.18")); + camera.Port.ShouldBe(51926); + camera.HomeKitInfo!.Category.ShouldBe(17); + camera.HomeKitInfo.IsPaired.ShouldBeTrue(); + camera.HomeKitInfo.DeviceId.ShouldBe("AA:BB:CC:DD:EE:18"); + } + + [Fact] + public void ParseMulticastResponses_DoesNotAssignUnrelatedAddressWhenSrvHostIsUnresolved() + { + var packet = BuildAnnouncement( + unrelatedHost: "other.local", unrelatedIp: "192.0.2.99", + instance: "Porch._hap._tcp.local", target: "missing.local", ip: null); + + MdnsClient.ParseMulticastResponses([packet]).ShouldBeEmpty(); + } + + private static byte[] BuildAnnouncement( + string unrelatedHost, string unrelatedIp, string instance, string target, string? ip) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.ASCII, leaveOpen: true); + writer.Write(new byte[2]); // transaction id + WriteUInt16(writer, 0x8400); // authoritative response + WriteUInt16(writer, 0); // questions + WriteUInt16(writer, (ushort)(ip is null ? 4 : 5)); // answers + WriteUInt16(writer, 0); // authority + WriteUInt16(writer, 0); // additional + WriteRecord(writer, "_hap._tcp.local", 12, EncodeName(instance)); + using (var srv = new MemoryStream()) + using (var srvWriter = new BinaryWriter(srv, Encoding.ASCII, leaveOpen: true)) + { + WriteUInt16(srvWriter, 0); WriteUInt16(srvWriter, 0); WriteUInt16(srvWriter, 51926); + srvWriter.Write(EncodeName(target)); + WriteRecord(writer, instance, 33, srv.ToArray()); + } + var txt = new byte[] { 5, (byte)'c', (byte)'i', (byte)'=', (byte)'1', (byte)'7', + 4, (byte)'s', (byte)'f', (byte)'=', (byte)'0', + 20, (byte)'i', (byte)'d', (byte)'=', (byte)'A', (byte)'A', (byte)':', (byte)'B', (byte)'B', (byte)':', (byte)'C', (byte)'C', (byte)':', (byte)'D', (byte)'D', (byte)':', (byte)'E', (byte)'E', (byte)':', (byte)'1', (byte)'8' }; + WriteRecord(writer, instance, 16, txt); + WriteRecord(writer, unrelatedHost, 1, IPAddress.Parse(unrelatedIp).GetAddressBytes()); + if (ip is not null) + WriteRecord(writer, target, 1, IPAddress.Parse(ip).GetAddressBytes()); + writer.Flush(); + return stream.ToArray(); + } + + private static void WriteRecord(BinaryWriter writer, string name, ushort type, byte[] data) + { + writer.Write(EncodeName(name)); + WriteUInt16(writer, type); WriteUInt16(writer, 1); // IN + writer.Write(new byte[] { 0, 0, 0, 120 }); + WriteUInt16(writer, (ushort)data.Length); + writer.Write(data); + } + + private static byte[] EncodeName(string name) + { + using var stream = new MemoryStream(); + foreach (var label in name.Split('.')) + { + var bytes = Encoding.ASCII.GetBytes(label); + stream.WriteByte((byte)bytes.Length); stream.Write(bytes); + } + stream.WriteByte(0); + return stream.ToArray(); + } + + private static void WriteUInt16(BinaryWriter writer, ushort value) + { + writer.Write((byte)(value >> 8)); writer.Write((byte)value); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/Fixtures/synthetic-plate.png b/tests/Heimdall.Infrastructure.Tests/Fixtures/synthetic-plate.png new file mode 100644 index 0000000000000000000000000000000000000000..248b75b26b2467ffdfdf7cc6df8e88fee5b26b17 GIT binary patch literal 13575 zcmeHuX*iYb+kH=^L8%NIl|-56q0Ew@(qtBrDIrrrnYKtprlLfqHpxtxGt;DyC_|== z$dFlL8{=L3`Msb2U*7lle|qoZIf#e*zOU;#&vmY~&Qp+<#wj}5eY6`kY@j=>uBNkL z!=_&wHvF@B+eUonNJo$*J~p0KQ`Yl{pX_lrWU{IL_}io`k%P}p?ZrO?ZF=K38wD;; z5X!~JR+dxuo^NIPY|jwEs{6q9<5dRYH2v9ZLuHyIJ^|+Jz{Eoxzj8-*YbcPIjG}Ga zDKUS2)@maKSxQHW--{5ZCmJNZ?!HajgvXk9I<&Im^M>Pfd{g*zd-MPB(?sYJXQipr zm@M_C_SRyoq}5Gq&Rg*X*YW?APv*P=wdP`h!PHGFRLf}>+}$52kAHLg6a0Ul{$E=l zUxZUA5D*fo@c2D2^!cf%S(W!teWZQ+tCTeA)mQ2|GSyRFT3YJq>4}eW&l>CM>b`yZ zhL3G+MPmmmDl7l4QZKvj*%|HQZ9Yd*qN1YQMw?SwTU(8buk}>jTKRtPT3^*OTr2BC zLqnbGZ{NOsuHsM2&dxqHHHD9wit~Cel@^zm<>ckF{?^X;>geb+K9hH!6wk=WFfuag z{P(I^Pih%uJ8&Q*p&!3S`uD17nkl`2Yubp`Lm zT)Vc+cYSRWlasnSIsyi-grr_OP^NnJ@7rhh`b%e5*D<+EBfozA8XFs%nljD1e8Sy* z0l(3fZS-d}Ex~7bG>y7)e81ql)t8-HR4-p1c&-$$@5SpD7SB%?>t|hfIYJ`7avf`YG*rA(gA zY47gn=;-QVUTR zQ0!)pdjldJNhd;1K4h~E9(1Z&8lG=AlRn{M8&g`cKgaq@?1TN%*i7f^*RQLqtNYUu zT1o2iE-o&YFJBIh^U~96MYwzzHg2?6l9wl9(Z;VGIxC6A;Z0mtS_Rf$#4SHoEDnSq zZmfIf+Rc0weO5gro#yJ|pFJbaj~&IG6B9X#Y`#4i92~^q3Y(P8HK&{%?kg)Oa77Gn z*~$8~z(&)Lrah^bgoC<-r6cZ^|8uRZtSl}4R%Bpe&`qN|DQ3OT(nTnKbnVI!`|sx_ zw=Ps4I(+#294k$JQ4!tFovSnNcQ=s~vnabF^zH1%mgmR&y#IWO5;jJ-M9(dxP%Mv< z%Wm5DR(L9U&E>}5y@I_%&{q1cSII8C&o(M(^&zjPpO2G5KuM1DeoanFN;)9#HaFVx zNoC)anqb1GhX>-q!#M`O87+24;PvsUy?DZxIO)D}cgEX=jqQ}w?kZ=d>SPxC}`hTbxYE^;a6{E`I2UXhuX{gN|!%uD`I!am>X-Ori66|XOtQF zrrfiLh?WY^KMlFkg@bSWHoY`1zOZ6okpJ<){`KYY94nt_i7G{;8D7No=f?;B{{9<% ze|{CPBt$!2BTcM)a&@W|mlhWr zNQ&};f@jI12lriRaLxFz=h~a(meCv9+S;jAPlS&iy@_+=>A5#-QtflAHk=dtC{g3( zc6&5AH8sHB-?6Lk^rW&-4T5xqG8q>U@q)s^?D!@2=!1PnyK*h=cHK?90_e)Aq+EO^ zcXPP$nX#5uB1Pt_L~yxAT8r?d5-myNZxwA>23u)pOe($fCzWsO)HXKm+Pxe2U)puo zFc_N^aQ{9FfsmmX$X(yi;JvmqvUL|*G>PSD}rc8=#{I+P5ZzB1RG-U}&OS@yAao?lrXU>du z~fXJ%%mz@{lvF)(Fuu0>P!{){tlz!7j+6T*U@IU{_rkdK4Ie0}Y& z-R_MqpO=g?3tvpGbF?)DY-Z(DWm1@qkCMyXojP(Y;%QcD$8)MlPoJjY)htj4fG&-- zwOYhIfzGIoyAH@T#LMbVDkt)PHzhlfOY&StGzuI=fTRKK2N|w6wt_|Lx|biGn5oJN0JXE0e_+d?LqYhdzG_-TQ*VBo=A) zIqK$g@87p~w_=IHxs-uxYpw=SLPnPdFOtMQMhY7Eto}Y#l(yjvFE8)N``t=^W2C1SMDuoD=qf8Kd&p#RPmiO6Lw{Ag$lK>|tr+~m10zY-XZBN-v{3mHrRTCT>yievjN4tXI-500AC}VB*2rdl`4TNTp z(M@NAah-1{#M)$QBi4S-^~2w<3}DLp==~5PMAWWtaT?iyHc+#tTRpH z8PECHxgT%urks6>bNlnof5*EKem*`!aD(L25%+l4BeSyXfjFuvDqV%PEy<@DrKO8` z*DLP-dugQEV?VIokabH00SX3cHm|Ob2#T;RXK}Kd1HIK!H-=rNA15S%tv{(8x$g*BNW;VeHVkJn6;+B~d$d zekKATX8G(EB5?(vit>6yQL%C-V`^HOQ)m8AQM>6%+U_#nwpS+Q64QIMoiwAUX=v4Z zHau2bGwiWy!)xxd1wMbhtV9)0Fbf$b*1wSQbzaZHnQhs!g?8^xdL<<#XZh3ntOTbJ zLZTHj@4}SUJZ1;$P<90Rmh2S0ErW@1QjSvB$cB1)$=;}K=DJ8L#w_<0FvDR9cY*Yi{@ zS6FgN%J#0)&0_f_@-i}o4xO`Kr28%vUo!zG__-YitXnnG=C!CPGWGoVa}ueqmuDxWo=JA>kG!#*?Rb^Y-oAdE|`VegE$E z?%wvjd-tZYmM12fe~uE?lxb^W2wq|AB_V03>DkhfV^-}m)|!F+6uDS<73)H|nf>#p zps0u-aa){?jSV!bz9NT%-;%WdKecfPWfoytZ|WZWYknE28ME$ZtnMsI0rc$%XKOt?J}x+uB{^=y?}TF`QYPrx<*$BC1aBYy61PKh zEemxf+qf7s?iI4bx+C6GMqb{1wApI7AqHU>{NTZ@$)a|F3)xr8zL=EV7)2Z$F*#OP zeomW@2%_vHJFqE5@xAf!gZnYF{ZtkGq$NnI9>gu&fvqOgtL15j&4HJCV zmipG$igR*ux?aS@ndbP8raWx~)c~#!<$U3V1Ze>iIzhd~>B`#+(c+dk-Fs?Ar=6P` z8-0KT_dZpvudRTg-*9tdCarG9K0F8wC4cwlB(L^XEG_i;`Yz25*|wy{ys8p4 z%>D7}+Y27r`xlHXos~Ri2lFgHF$M5de>Tz4X+|+31k}Dd6~>;Vp-^&jJSvsjI*scc568vIr+@JSA0ZvV7PyHn6kDq4gKakSoE_ zD9R3PnUU#*5PKoPI;bGR_XeXc2c15vtEDxAlM4J2FJ|!$l}%KtpfEl@{@BVy!QoR6 zH*emYE+52SQeKYDF$Y6~RwA&oGcrnoDEH@m70VKw0^LM1>asSY)S!k7u9tbwkF`PR z(yCr*MU_x+uDmb&cr!%BH{qT^fsi}&KP^X#G;}kW# zDO6BKC8M6u1+dQD>Uk6Sy;Ex z6}%d#f;f$jXY=O_OW>5eQoG0B_QZ)37pfA8US4J4Y?_*yoU*qc)jt&#lrRHDzH{@*>Je0l4#%=2*;;2D+AiZSiPI|n0LwSp0hlZvG@GC zsoTz}cAkqpl5z6EzNBW93}|dY0lIzGCu&S;{U)ow-x#Vfv8mbG<37>h{PQE-kSu(i zuJW4)g*xGsfKWw_1YX>1LSPZOw8ur;1bBV4bZz0M+e8Q0oS2x_l60k3V`t~m&oCus z*4i!!v4A2bch0oO?djS-bL`)E5{XJkE!qf!Y{N&O($Z8e> z4P8Oh0Q=s(8LO{ZQ1+I)-O^VRS5OM2oO-kI9ME1xm%+gB^pONOE4$2-)6@AlWg)=m zA6r_Z9Dr!P443Fa3H>C>)|?DOMccgtQKVfJyH_o*pny2vW^f|Kq{`c9>6Ue(=XV|Q z`5UBjdAf#OCdI(inL)w#jxVn7`SOCs-e& zp{@N5`}Qg9pc!nM4Ba%^($U8-xyIVE;3;G()V~W_w$n~)QCuLqCM9vGfwynmgwmo- z);=WLE6H@R!1}>#aSU(5Zb^@sA9uIz7N`>icdqhYDsle#I^jH zCYH;>wM0IbqX0t`j^{&MBDMvZkPf3Ac`s(!N||zq2N)T3b4(SBY{U~#YXgJrTGJn; z^KH{ZspUP`C20!3Zg8M6?6BXJOd4a!@>;Mho+}R$98Rr zY5+a~a>}pwt6aK7Ui|%2@IrPvMJ{&UW~)szu<(lG0KL{83a+V8HboH}r^XhAemA&WvT{ zP#rVRCm|u9ar4Oa$XsuD;Vo&JzWx3zRakLh;gOnAH@dK^ebK@kjltODh6zSjFmFo*9YH9M~GkX^XRdCay4oY!rZe;&$3=f+A5dF&PH$fB*dC->|zM$n*`G6Qp_j>G77drrk=b z99(DIw%oOVp$ms&qtoQI{v0#END)y{O={$O@bLC!{iwqu^<_0r)~(O;LZQ&NojID3 zp8hLB^Vn!x)>HihWp_Q}Wt6QTS$AEkHgpBglCY2kM zf1GAYntDUqznR(n-zby{A)Y%2p>M+!AR{LiHF>WUzAe$igOBXx;xbE8Br*kD?S=h( z=gu9x{BsJ&*N3PITeofvDf6_z(fR(JH`w+3uRer-ApK$MCelj^2M=%VeP_R_nxvBV z4uwW!eYpZ8Yx*aEUMEmS!JG;mEiDeNT*L{!jGH~%R`kVOY<1jhT@J;&>uz*- zNJvO}`jaP2+S+^0wz}Vtd-hOipN9k;^8$Jr^6pc7J7KnrqE5uDFMR#_6{fa8JSPam z5?ylk2T)_BwMEOKwAqAe?f@vq8#3j6>FJ1B;!o;gH-FlA>9NS0!M%0>8a&z{`^83XNpCgXe= zt}!;3IP%OLQgUE))V3@G{Cf_9C{D!81pW~-fjjqrN;Y65B$#3Go}biS-3qm#XyuC+ zW6_|S?a8-o;qi}PlevC;i4__fEie_zxxCt1^&#ESGe+d~?}+qI5BBp?k}BckL^?)? zhVJyUWS#EFv!r!@p+a>o*7#a)ZKFkPJTuV^33hk~Ep4lh;Q)a^puXY9(7nJr`jT>X zq_e#1@VQRwf|>Sd2=Eh*-#&lNawu1)jrv2;yI8a1G40;o#zu_@-{V>h(Idx$I4{Z% zfIhekrKOjZm%C4qjV#pR>QFn6Vjs-Kgg~n;0EVT!}1w-45bc~$np#|Cf4=HXYgu$wi*EKE$^aJ?=|3V+bmROBA} zcp4ry7(WXGjo-k)KNHDASw-JO}=xf3jmouJTe!-B&53oK^i3?H4Cu)9u)PXSCp&;$i{cC_bD_M0XtQw!s0M&DK>;l}&=K?# zgv_cc!V4kRuezA1`#B0pNkxeggzEuSG^tbyJIS;FUtCyN7}of?0WeQ^0a`@b2*#TY zF33R@mqc-!CXyoXv_n3{MtQk!moWQDC4 z^AQkeLQ#DmS~e+%4#X2`H7f1!l)%n zUAnRTV`E(zy1bm)SSaDKr7ej#C9ACszfD739g0@sb8YP++L<(4XiJ?AAJIHqa|=BW z3<=n2TBtxM!xhy3cf;II+AoH0I*h95h+Z@X2~?WV$A2npoZ8>*9c84h9vIH%S1g#% zheFR7EoJ#}r=KlfoO|CbgCG4AEHu!IUb*{-4%t7O*Rnsme_UI;=9#WlV$104?5rs) z(A~!tkL#KLJ|qAwKp>=ZS5;N1xD0kV7r^1YZguk$mHgBPfw%j)s zeam{0Zwhu}Yz1jl6MZMJi6jbBYRc-X;u>}Z53S6E9K*b%plR3Dg>yF+JYZv>QYb+0 zY^+Y3ou7v;RKI>bH~shnXLom&$GQQ8!eo!XWAn@CMKvEQ^wk07p>#VzncH&n@`kaB zzvGze4czFYw#~6c#kn{@^;^x6b#Te6JEb*0H=XlvTf(RfYWB=mxF`T zmt&P8&06W2CMPGMeNKX2QHKZM2B^_I1Zx7=B|YS`*SEG#4QI2lv4PA=$0!Bd97a|d zw+X|%d3x^p+S*^uDW6AM(rP|dp(A^F({qbv7I#6TYbnvMS(^9-1Q>4CN1(EXv#HzQ z>><*Ux{#S8JfxlQL`_)GHiqY1G>4clH@6iCKDhNp$={n1Rdlqp!66}x z`&Swyo8~6F4IFrmoLe4vwN!9wP3?V{G!M_oR>E?Z&-5pyC6q=iL14_7pO-fc>}PeM zdY$k%)f3-jc&z(eg@#i$%J#<_zm1~WZKF2;^*$(qo3{wiv#`JokwLgeVtGYy+EDcg0-awDqw^cjwb{5(e z!!%ZCmnCh)pbbv0Ia6Oy+b?zjKtnZc)b)@x{)2|um~m)@o^lw5GpaW+MJy6ygjIur6y@7`L*tJB&eLqnCb^@7k@NgGi( z0s72S=(T}W_ZHZMrN059rl+UdkUUT7C7%8ZJ`c2YgES46geF%tw{P`!c6W1I8we4- z_ele3x>y$9E8EmlqcUW6%HTDzZ=WzMmzt z4veSv5>`1CW)s#|d6ksRYEJ2)KzwN)y@6&R+TmUPJ6IZ&(1v*3k;8*d>X&uCh8(Db zjqY8CsU3!p5XpZ#4A|3^@qLM?N`kJbV@{fII6E*(fckxnH0=NlD=8`YxuTrouqBC= zJD?+GIm1?ts=ZxAuQp+frO0L@F8<_Cz=?3wz-C2X$N4drK^VG06_0! zWSo=2k4S#5tBX-2QsQM@0oW4O4bk9i(Ibf;D~Ste#vGoRAD^DinRF!|TmqcH1>zZt zat)&@0x_}c*!StGl~-|baUIv6X&4w9mLMQu>OrOGdX(&C-5G#ZEW|CY(9lry?Qucm zQ!VokL5w3!3DVu2#~|P#Bcy7kw{_XP4%>DaT&-@_-Hes)}%|VoevOQ0`I@;^H0gj%G%o6VkKe0!LgWhIxAX<{N=q8 zTAiu&{2h#^`dk|>tE8T*8jl`5vLa3}xxZIpS~wLeS}}ZfLkNJ#<;JhhqXy* z-8*K1A=$d2<;90RMw*fIH~oggIaTisvO1y1J6-YT;iKwmUcohv+cR+{U85c=;}sI))3(ZBL&e#uUIUInz5x$H&uAL_UAF5 z&1n}k%1=ho20fMj#)GaMd}2hZb){)vuEl%YWDDIs4WwiWs>;S*UllYk%dqM(6|I?t}+Vb@Up7 z0s~82M;@Zz9iCCBoYPLVekS=hgir@+AnXV^T*e@nc!eVl9bcQ8sFPfHSPt6$2-t`S zU6>&b4i0#0R~MHla%lvK((4R3HRtS-h9B9ft8h&p1yx@Fqy&; z9`|ItwqXq^EWEl+>4LkbKUSOWE~^@-rWDp5kAK|$29kXbgzMVLR?p3gatn}XHS zZr`p=q&-Rp4>-=L3jd6*pXq;J?9i!$(Y&Iqe$2H7WH^W*8_5bbzrH@NSFJzS`qpPx z8Ox5{yM5t4!_PdP0kd$he7Z`PNIU=FfIJ0e_V9$w14uBy$#)>uxjc$^c7%7$EzED1e_ z@lg*iFYH&GB$=HBjF~{tFL!gqIu8LdYgo(_FuI4-Ya`KIJZ$7_R&xD$I9rj(*<11H zs%uG+v=hh&@3t`DZ%_lrsB4Gj062Z`av)M z)X|H+bFN15Kl4TPt`3fl!WKPw7`515s{a+rWxA(4P2rRXY6$SslTtPtrxK{+#gwc&68)g31Onv+QcmCDuYw}yWEaW5z3n0K&SFZ3iZKtEd zPiD@t`D4lcCraY;<;R)44y|F3mXLh7rR6MTsCzxQ$m&cM9!DL(g@y_X3+pP_ z!1oM%A1*^vylg~~Zm3?R*F1h?vZq{{k57Hl=*;l+v=TNKOi6I-*82!>2apC%P74gN z2p!lY8J=2_mXhMwS7qY)@Wl(uYM;MPMz(!JTMdaN&?M_IV-Dz;WeXXam{7R!>nmy( zD0D6=9^Ajg8{nQtq1Z8;gOQC)#Sm{4ZFi6~r!GZjDgVf+PX5*QYS%`WaLh`x)5 z;Pt6! z?bd^QO?iCai96}&Ch^O7-IDsP;o2~Dc{Ji>AoJzrZF{c?>7o%0JG&Tc8(lGgEJ7|* z@zJZxHNluK{rHa`=16Lk5|j*#Ui9~CgBC!SA;QOFY)HQ;lvlcG zyX@tog17XlhkEv|y~N>~mAagmlM%S?>iW5%L63xn`JVmz%dzN9cyoC-A+&2ft!phcCMn}Ndqqv{10oe-?DAOLZ!mH}jA%hjV$_Qhid1>`K*Y8r+^ECTGyC8BnYkr zXEz^2qosdx(qvV5?~Vt?sTe+{4pS4)UA%bl0`>a-qOV9J&2{x|c{%a-?_rpd@YLJ? zV{v29$=h+`Hnso!{RBs{#@PZkF8s-Z`IrCUA8Y*Ium4Z~+~xoG4o;}ijLv&$Yvc4c ztlc~Ozw#$L|GkE}Eq9eC_fl{C + + + + - \ No newline at end of file + diff --git a/tests/Heimdall.Infrastructure.Tests/PlateOcrTests.cs b/tests/Heimdall.Infrastructure.Tests/PlateOcrTests.cs new file mode 100644 index 0000000..9338803 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/PlateOcrTests.cs @@ -0,0 +1,44 @@ +using Heimdall.Infrastructure.Services; +using Shouldly; +using Xunit; + +namespace Heimdall.Infrastructure.Tests; + +public sealed class PlateOcrTests +{ + [Fact] + public void Parses_synthetic_tsv_word_and_confidence() + { + const string fixture = "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft\ttop\twidth\theight\tconf\ttext\n" + + "5\t1\t1\t1\t1\t1\t0\t0\t100\t30\t92.5\tAB-123-CD\n"; + + var result = TesseractPlateOcr.ParseTsv(fixture); + + result.ShouldNotBeNull(); + result!.Text.ShouldBe("AB-123-CD"); + result.Confidence.ShouldBe(0.925); + } + + [Fact] + public void Rejects_empty_or_unconfident_tsv_rows() + { + var result = TesseractPlateOcr.ParseTsv("header\n5\t1\t1\t1\t1\t1\t0\t0\t1\t1\t-1\t"); + result.ShouldBeNull(); + } + + [Fact] + public void OCR_options_are_bounded_when_enabled() + { + new PlateOcrOptions { Enabled = true, MaxImageBytes = 128 }.IsValid().ShouldBeFalse(); + new PlateOcrOptions { Enabled = true, TimeoutSeconds = 100 }.IsValid().ShouldBeFalse(); + new PlateOcrOptions { Enabled = false, MaxImageBytes = 0 }.IsValid().ShouldBeTrue(); + } + + [Fact] + public void Accepts_bounded_synthetic_plate_crop_and_rejects_invalid_bytes() + { + var fixture = File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Fixtures", "synthetic-plate.png")); + TesseractPlateOcr.IsSafeImage(fixture).ShouldBeTrue(); + TesseractPlateOcr.IsSafeImage(new byte[32]).ShouldBeFalse(); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/Storage/RecordingStorageQuotaOptionsTests.cs b/tests/Heimdall.Infrastructure.Tests/Storage/RecordingStorageQuotaOptionsTests.cs new file mode 100644 index 0000000..5f36f76 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/Storage/RecordingStorageQuotaOptionsTests.cs @@ -0,0 +1,27 @@ +using Heimdall.Infrastructure.Storage; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests.Storage; + +public sealed class RecordingStorageQuotaOptionsTests +{ + private readonly DataAnnotationValidateOptions _validator = + new(RecordingStorageQuotaOptions.SectionName); + + [Fact] + public void PositiveQuota_IsValid() + { + _validator.Validate(RecordingStorageQuotaOptions.SectionName, + new RecordingStorageQuotaOptions { MaxBytes = 24 }).Succeeded.ShouldBeTrue(); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void NonPositiveQuota_IsRejected(long maxBytes) + { + _validator.Validate(RecordingStorageQuotaOptions.SectionName, + new RecordingStorageQuotaOptions { MaxBytes = maxBytes }).Failed.ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs index b2c06a3..1732bc0 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/PostgresTestBase.cs @@ -23,7 +23,7 @@ public abstract class PostgresTestBase : IAsyncLifetime protected PostgresTestBase(PostgreSqlContainerFixture postgres) { _postgres = postgres; - _connectionString = postgres.ConnectionString; + _connectionString = postgres.IsAvailable ? postgres.ConnectionString : string.Empty; _factoryLazy = new Lazy( () => new HeimdallWebApplicationFactory(postgres.ConnectionString)); } diff --git a/tests/Heimdall.IntegrationTests/Controllers/RecordingQuotaTests.cs b/tests/Heimdall.IntegrationTests/Controllers/RecordingQuotaTests.cs new file mode 100644 index 0000000..ee6166f --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/RecordingQuotaTests.cs @@ -0,0 +1,200 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.IntegrationTests.Factories; +using Heimdall.TestCommon; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.EntityFrameworkCore; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public sealed class RecordingQuotaTests : PostgresTestBase +{ + private readonly PostgreSqlContainerFixture _postgres; + + public RecordingQuotaTests(PostgreSqlContainerFixture postgres) : base(postgres) + { + _postgres = postgres; + } + + [Fact] + public async Task ConcurrentAgentUploads_DoNotExceedConfiguredCentralQuota() + { + if (!_postgres.IsAvailable) return; + + var storage = new BarrierRecordingStorage(expectedConcurrentUploads: 2); + await using var quotaFactory = new HeimdallWebApplicationFactory(_postgres.ConnectionString, + recordingQuotaMaxBytes: 32, + configureTestServices: services => + { + services.RemoveAll(); + services.AddSingleton(storage); + services.RemoveAll(); + services.AddSingleton(storage); + }); + + var admin = await quotaFactory.CreateAdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", new + { + name = "Recording quota site", + timezone = "UTC" + }); + siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + using var site = JsonDocument.Parse(await siteResponse.Content.ReadAsStringAsync()); + var siteId = site.RootElement.GetProperty("id").GetGuid(); + var registrationToken = site.RootElement.GetProperty("registrationToken").GetString(); + registrationToken.ShouldNotBeNullOrWhiteSpace(); + + var registerResponse = await admin.PostAsJsonAsync("api/agents/register", new + { + token = registrationToken, + hostname = "recording-quota-agent", + version = "quota-test", + publicIp = (string?)null + }); + registerResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + using var agent = JsonDocument.Parse(await registerResponse.Content.ReadAsStringAsync()); + var agentId = agent.RootElement.GetProperty("agentId").GetGuid(); + var apiKey = agent.RootElement.GetProperty("apiKey").GetString(); + apiKey.ShouldNotBeNullOrWhiteSpace(); + + var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name = "Quota camera", + rtspUrl = "rtsp://quota-camera.invalid/stream", + manufacturer = "test", + model = "test" + }); + cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + using var cameraJson = JsonDocument.Parse(await cameraResponse.Content.ReadAsStringAsync()); + var cameraId = cameraJson.RootElement.GetProperty("id").GetGuid(); + + var assignmentResponse = await admin.PostAsJsonAsync("api/assignments", new + { + cameraId, + agentId, + reason = "quota-test" + }); + assignmentResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var enableResponse = await admin.PutAsJsonAsync($"api/cameras/{cameraId}", new + { + name = "Quota camera", + rtspUrl = "rtsp://quota-camera.invalid/stream", + status = "Online", + recordingEnabled = true + }); + enableResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + + using var agentClient = quotaFactory.CreateClient(); + agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey); + var timestamp = Uri.EscapeDataString(DateTime.UtcNow.ToString("O")); + // Force two first attempts with the same id to finish object upload before either + // can persist metadata. The loser must not overwrite the winner's object key. + var racedId = Guid.NewGuid(); + var racedUploads = await Task.WhenAll( + UploadAsync(agentClient, cameraId, racedId, timestamp, "....ftyp....AAAA"u8.ToArray()), + UploadAsync(agentClient, cameraId, racedId, timestamp, "....ftyp....BBBB"u8.ToArray())); + racedUploads.Select(response => response.StatusCode).Distinct().ShouldBe([HttpStatusCode.OK]); + string racedStoragePath; + await using (var scope = quotaFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + (await db.Recordings.CountAsync(recording => recording.Id == racedId)).ShouldBe(1); + racedStoragePath = await db.Recordings.Where(recording => recording.Id == racedId) + .Select(recording => recording.StoragePath).SingleAsync(); + } + var racedKeyParts = racedStoragePath.Split('/'); + racedKeyParts.Length.ShouldBe(4); + racedKeyParts[0].ShouldBe("recordings"); + racedKeyParts[1].ShouldBe(cameraId.ToString("D")); + racedKeyParts[2].ShouldBe(racedId.ToString("D")); + Guid.TryParseExact(Path.GetFileNameWithoutExtension(racedKeyParts[3]), "N", out _).ShouldBeTrue(); + storage.ObjectCount.ShouldBe(1); + + var firstId = Guid.NewGuid(); + var secondId = Guid.NewGuid(); + var responses = await Task.WhenAll( + UploadAsync(agentClient, cameraId, firstId, timestamp), + UploadAsync(agentClient, cameraId, secondId, timestamp)); + responses.Select(response => response.StatusCode) + .OrderBy(status => (int)status) + .ShouldBe(new[] { HttpStatusCode.OK, (HttpStatusCode)507 }); + var denied = responses.Single(response => (int)response.StatusCode == 507); + (await denied.Content.ReadAsStringAsync()).Contains("quota exceeded", StringComparison.OrdinalIgnoreCase) + .ShouldBeTrue(); + storage.ObjectCount.ShouldBe(2); + + var accepted = responses.Single(response => response.StatusCode == HttpStatusCode.OK); + using var acceptedJson = JsonDocument.Parse(await accepted.Content.ReadAsStringAsync()); + var acceptedId = acceptedJson.RootElement.GetProperty("id").GetGuid(); + await using (var scope = quotaFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + (await db.Recordings.CountAsync()).ShouldBe(2); + (await db.Recordings.SumAsync(recording => recording.SizeBytes)).ShouldBe(32); + } + + var retry = await UploadAsync(agentClient, cameraId, acceptedId, timestamp); + retry.StatusCode.ShouldBe(HttpStatusCode.OK); + storage.ObjectCount.ShouldBe(2); + } + + private static Task UploadAsync(HttpClient client, Guid cameraId, Guid recordingId, + string timestamp, byte[]? bytes = null) + { + var content = new ByteArrayContent(bytes ?? "....ftyp....1234"u8.ToArray()); + content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4"); + return client.PutAsync( + $"api/cameras/{cameraId}/recordings/{recordingId}/content?timestamp={timestamp}&durationSeconds=1", + content); + } + + private sealed class BarrierRecordingStorage(int expectedConcurrentUploads) : IRecordingStorage, IStorageObjectDeletion + { + private readonly ConcurrentDictionary _objects = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _uploadBarriers = new(); + private int _uploads; + + public int ObjectCount => _objects.Count; + + public StorageLocation CaptureCurrentLocation() => + new(StorageProvider.Local, LocalRoot: "/quota-test-recordings"); + + public async Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, + CancellationToken ct = default) + { + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + _objects[key] = buffer.ToArray(); + var uploadNumber = Interlocked.Increment(ref _uploads); + var batch = (uploadNumber - 1) / expectedConcurrentUploads; + var barrier = _uploadBarriers.GetOrAdd(batch, + _ => new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); + if (uploadNumber % expectedConcurrentUploads == 0) + barrier.TrySetResult(); + await barrier.Task.WaitAsync(ct); + } + + public Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default) + => Task.FromResult(_objects.TryGetValue(key, out var bytes) ? new MemoryStream(bytes, writable: false) : null); + + public Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, + CancellationToken ct = default) + => Task.FromResult(null); + + public Task DeleteBatchAsync(IReadOnlyCollection keys, StorageLocation location, + CancellationToken ct = default) + { + foreach (var key in keys) _objects.TryRemove(key, out _); + return Task.CompletedTask; + } + } +} diff --git a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs index f09f696..9392097 100644 --- a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs +++ b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc.Testing; using Heimdall.Application.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using System.Globalization; namespace Heimdall.IntegrationTests.Factories; @@ -13,11 +14,16 @@ namespace Heimdall.IntegrationTests.Factories; public class HeimdallWebApplicationFactory : WebApplicationFactory { private readonly string _connectionString; + private readonly long? _recordingQuotaMaxBytes; + private readonly Action? _configureTestServices; /// Creates a factory connected to a real PostgreSQL instance via Testcontainers. - public HeimdallWebApplicationFactory(string connectionString) + public HeimdallWebApplicationFactory(string connectionString, long? recordingQuotaMaxBytes = null, + Action? configureTestServices = null) { _connectionString = connectionString; + _recordingQuotaMaxBytes = recordingQuotaMaxBytes; + _configureTestServices = configureTestServices; } protected override void ConfigureWebHost(IWebHostBuilder builder) @@ -27,6 +33,8 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory builder.UseSetting("ConnectionStrings:Default", _connectionString); builder.UseSetting("Database:MigrateOnStartup", "true"); + if (_recordingQuotaMaxBytes is long maxBytes) + builder.UseSetting("Recordings:StorageQuota:MaxBytes", maxBytes.ToString(CultureInfo.InvariantCulture)); // JWT config builder.UseSetting("Jwt:Key", "ThisIsATestKeyThatIsAtLeast32BytesLong!"); @@ -43,6 +51,7 @@ public class HeimdallWebApplicationFactory : WebApplicationFactory { services.RemoveAll(); services.AddScoped(); + _configureTestServices?.Invoke(services); }); } } diff --git a/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs b/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs new file mode 100644 index 0000000..6649725 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs @@ -0,0 +1,26 @@ +using Heimdall.Api.Controllers; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Services; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using NSubstitute; +using Xunit; + +namespace Heimdall.Web.Tests.Controllers; + +public sealed class PlateRecognitionControllerTests +{ + [Fact] + public async Task Recognition_is_disabled_by_default_and_does_not_call_OCR() + { + var config = Substitute.For>(); + config.CurrentValue.Returns(new PlateOcrOptions()); + var service = Substitute.For(); + var controller = new PlateRecognitionController(null!, service, config); + + var result = await controller.Recognize(Guid.NewGuid(), null, CancellationToken.None); + + Assert.Equal(503, Assert.IsType(result).StatusCode); + await service.DidNotReceiveWithAnyArgs().RecognizeAsync(default, default, default); + } +} diff --git a/todo.md b/todo.md index d0eecf1..ede68d8 100644 --- a/todo.md +++ b/todo.md @@ -32,25 +32,25 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. - [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. -- [ ] **AGENT-08** Reconnexion, remplacement atomique du snapshot caméra et ACK exact par digest sont couverts par les fixtures SignalR/HTTP de `ConfigReceiverServiceTests`. L’ACK réessaie maintenant jusqu’à trois fois après une erreur transitoire (test 503 puis 204 : 1/1; suite Agent de référence avant ce changement : 388/388). La suite Agent passe maintenant 389/389 après ce changement; la recette Compose isolée reste à lancer quand le créneau Docker sera libre. La validation sur Agent déployé avec caméra réelle et coupure réseau reste ouverte. +- [ ] **AGENT-08** Le Central simulé par Kestrel sert une configuration une seule fois; l’Agent applique une fois son snapshot, envoie deux ACK avec le même digest après un HTTP 503, puis Central persiste exactement un ACK avec HTTP 204. Test ciblé 1/1 et suite Agent 399/399 réussis localement. La recette Compose isolée construite depuis les dépendances source avec SDK 10.0.100 a exécuté le test Kestrel : configuration GET une fois, ACK même digest après 503 puis 204, application snapshot une fois, résultat 1/1. Le projet `hmdack_8df77197` a été démonté; conteneurs, volumes, réseau et source temporaire vérifiés/supprimés à 0. La validation sur Agent/caméra réels et coupure réseau reste ouverte. - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. - [x] **Accès caméra #141** Les PR #65/#88/#100 valident API, remplacement UI atomique, chargement paginé, protection du brouillon et révocation des grants excédentaires (>500). Validation complétée sur la branche de clôture : `ResourceAccessTests` vérifie l’union direct + groupe et la révocation live; `HttpIsolationTests` exerce le pipeline HTTP avec périmètres; un test bUnit `GroupsPage_GererAccesCamera_AfficheSiteEtAccordePuisRetireLaCamera` vérifie l’affichage site/caméra et les appels d’ajout/retrait depuis l’UI. Les tests couvrent les priorités d’accès dans l’interface et la révocation; aucune caméra physique n’est requise pour cette gestion des autorisations. Skill dédiée : `skills/camera-access-groups/SKILL.md`. - [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel. -- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Restent l’aller-retour S3 et les mesures RPO/RTO sur installation/données réelles. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. +- [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Le 5 novembre 2026, le projet `hmdbk_a466d0ce` a vérifié le dump S3 daté, `latest.sql.gz`, sa restauration avec retour de `after-backup` à `before-restore`, l’upload protégé et le miroir RustFS/manifest. La recette a aussi révélé que l’ancien téléchargement de `mc` échouait en HTTP 410 et que BusyBox `date` ne calculait pas les seuils relatifs; Compose installe maintenant AWS CLI, Bash et GNU coreutils, et chaque appel AWS reçoit les clés configurées. Une nouvelle acceptance depuis `docker/docker-compose.backup.yml` + overlay jetable a vérifié le roundtrip PostgreSQL `after-backup`→`before-restore`, la purge de clés journalières et hebdomadaires anciennes, le manifeste RustFS et l’upload protégé; teardown vérifié à 0 conteneur/volume/réseau. Les mesures RPO/RTO sur installation/données réelles restent externes. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. ## P2 — fonctionnalités et exploitation - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. -- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. Un vertical initial ajoute le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read Data Protection à durée limitée, la revalidation des droits caméra et un lecteur WHEP dans le détail caméra ; audio/PTZ restent exclus. Les builds/tests ciblés API/Web (7 tests) et Agent (1 test), la syntaxe JS et `git diff --check` passent. La recette Compose jetable a validé bootstrap admin/site, enregistrement Agent, caméra RTSP synthétique assignée/activée, demande publish-session et démarrage du relais, ticket read autorisé + callback MediaMTX 200, rejet ticket forgé 401 et rejet caméra inconnue. Une requête WHEP avec SDP invalide a atteint MediaMTX et retourné 400; aucun navigateur/frame décodée ni arrêt par désactivation API n’a été vérifié. Compose `hmd-webrtc-e9e542` a été arrêté avec `down --volumes --remove-orphans`, puis ses conteneurs, volumes et réseaux vérifiés absents; les secrets/cache acceptance ont été supprimés. Validation caméra physique, LAN, TURN externe, lecture d’une vraie offre SDP et cycle désactivation restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. -- [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Après correctif, un conteneur basé sur CUDA sans device a répondu 200 sur `/health/live`, mais une publication Agent CPU bind-mountée masquait ses bibliothèques ONNX GPU; l’absence de Central/token a aussi interrompu l’enregistrement. Cela valide le garde-fou startup, pas le paquet GPU final. Restent rebuild de l’image GPU post-correctif, acceptation avec Central + token et preuve d’inférence CPU sans device, puis GPU NVIDIA réel. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. +- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut, limites fichier/dimensions/délai et suppression du crop temporaire. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. L’acceptation Agent n’est pas concluante: les `docker create` de `agent-state-init` sont restés bloqués/ont fait conflit dans le daemon partagé; aucun Agent GPU n’a démarré, donc pas de preuve healthz/enregistrement/inférence CPU dans cette image. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent l’acceptation complète de l’Agent CUDA sans device (inscription, frame synthétique et inférence CPU effective), puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. -- [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. +- [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` à revérifier après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. - [x] **UI groupes #138 / accès #134** L’éditeur permet de parcourir les comptes par nom/e-mail, de lister et retirer les membres, et d’accorder/révoquer les accès caméra avec nom de caméra et site. Le 4 novembre 2026, la revue a trouvé puis corrigé le POST membre qui visait une route inexistante; le client utilise désormais `POST /api/groups/{groupId}/users/{userId}` et `GET /api/groups/{groupId}/users`. Vérifications : Web groupes + client API 39/39; matrice d’autorisation Web 14/14; CameraAccessService Infrastructure 25/25; scénario PostgreSQL relationnel 1/1 valide l’union direct/groupe, le maintien du droit restant après révocation de l’autre, puis l’arrêt du grant d’un groupe supprimé. Recette Compose source jetable : bootstrap Admin, création groupe, ajout/liste/retrait membre et liste vide, tous HTTP 200; conteneurs, volumes, réseau et secrets temporaires vérifiés supprimés. Skill : `skills/group-access/SKILL.md`. - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; reste une validation de scraping sur un déploiement et l'évolution réelle des mesures. -- 2.54.1 From a92332465c65ede410797f18fbc258ad4d2a994c Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 11:28:56 +0100 Subject: [PATCH 17/40] fix: expose opt-in plate OCR in server installs --- .env.example | 3 ++ docker/docker-compose.prod.yml | 1 + docker/docker-compose.yml | 1 + docs/docker-compose.md | 26 +++++++++++++++++ install/install-server.ps1 | 3 ++ install/install-server.sh | 3 ++ skills/deployment-guide-acceptance/SKILL.md | 31 +++++++++++++++++++++ todo.md | 16 +++++------ 8 files changed, 76 insertions(+), 8 deletions(-) create mode 100644 skills/deployment-guide-acceptance/SKILL.md diff --git a/.env.example b/.env.example index a1cb0bf..619983b 100644 --- a/.env.example +++ b/.env.example @@ -23,6 +23,9 @@ JWT__REFRESHKEY=ChangeMeToAtLeast32BytesRefreshKeyInProd! JWT__ISSUER=heimdall JWT__AUDIENCE=heimdall-api +# Optional manual license-plate crop OCR (disabled by default). +PLATE_OCR_ENABLED=false + # ASP.NET ASPNETCORE_ENVIRONMENT=Development ASPNETCORE_URLS=http://+:8080 diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index 8adb32f..c455fbb 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -54,6 +54,7 @@ services: LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776} + PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false} Sentry__Dsn: ${SENTRY_DSN:-} Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05} Sentry__Release: ${SENTRY_RELEASE:-} diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 164655c..87bae7f 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -44,6 +44,7 @@ services: LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-} LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-} Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776} + PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false} ports: - "${WEB_PORT:-5000}:8080" volumes: diff --git a/docs/docker-compose.md b/docs/docker-compose.md index 67cc636..7ec2aef 100644 --- a/docs/docker-compose.md +++ b/docs/docker-compose.md @@ -99,6 +99,23 @@ unset db_password docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d ``` +Central images also include Tesseract OCR and its English language data. The +manual license-plate crop reader is opt-in and defaults to disabled. Core and +production Compose files, plus both server installer templates, map +`PLATE_OCR_ENABLED` to Central's `PlateOcr__Enabled` option. Installer-generated +`.env` files set it to `false`; set `PLATE_OCR_ENABLED=true` and recreate the +Central service to enable the feature. Existing installer upgrades preserve an +existing value and add `false` only when the key is absent. + +When enabled, an authorized operator can upload a JPEG/PNG plate crop from the +camera detail page. Processing runs on Central; the temporary crop is removed +after processing, while the candidate text and history event are persisted. +The feature limits uploads to 512 KiB and images to four megapixels. It does +not detect plates in video or perform face recognition, and the OCR result is +not a verified identity. Review retention/privacy implications in +[`skills/vision-identity/SKILL.md`](../skills/vision-identity/SKILL.md) before +enabling it. + The development Compose builds Central from the local source and starts only Central plus PostgreSQL: @@ -106,6 +123,15 @@ Central plus PostgreSQL: docker compose --env-file docker/.env -f docker/docker-compose.yml up -d ``` +For a disposable local installation, copy `.env.example` to an ignored +temporary env file, replace the sample database/JWT values with generated +values, and choose unused loopback ports. Use a unique Compose project name and +`HEIMDALL_NETWORK_NAME`; after checking `/healthz`, stop only that project with +`docker compose -p ... down --volumes --remove-orphans`. Verify its +containers, volumes, and network are gone. Never use `.env.example` unchanged +for an exposed or production deployment. The disposable recipe is maintained +in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-acceptance/SKILL.md). + ## Agent Prefer the Compose shown in the Central UI's site installation panel. It uses diff --git a/install/install-server.ps1 b/install/install-server.ps1 index 5f4f04f..68a7c1c 100644 --- a/install/install-server.ps1 +++ b/install/install-server.ps1 @@ -145,6 +145,7 @@ Cors__AllowedOrigins=$corsOrigin TZ=Europe/Paris REDIS_PASSWORD=$(New-RandomHex) HEIMDALL_DATA_VOLUME=heimdall_heimdall_data +PLATE_OCR_ENABLED=false "@ [IO.File]::WriteAllText($envPath, $envContent.TrimStart("`r", "`n"), [Text.Encoding]::ASCII) Set-PrivateAcl -Path $envPath @@ -165,6 +166,7 @@ HEIMDALL_DATA_VOLUME=heimdall_heimdall_data $envContent = Ensure-EnvValue $envContent 'TZ' 'Europe/Paris' $envContent = Ensure-EnvValue $envContent 'REDIS_PASSWORD' (New-RandomHex) $envContent = Ensure-EnvValue $envContent 'HEIMDALL_DATA_VOLUME' 'heimdall_heimdall_data' + $envContent = Ensure-EnvValue $envContent 'PLATE_OCR_ENABLED' 'false' [IO.File]::WriteAllText($envPath, $envContent, [Text.Encoding]::ASCII) Set-PrivateAcl -Path $envPath } @@ -205,6 +207,7 @@ services: ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT} ASPNETCORE_URLS: http://+:8080 Cors__AllowedOrigins: ${Cors__AllowedOrigins} + PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false} ports: ["${WEB_PORT}:8080"] volumes: - heimdall_data:/var/lib/heimdall diff --git a/install/install-server.sh b/install/install-server.sh index 8930a26..7e64e38 100755 --- a/install/install-server.sh +++ b/install/install-server.sh @@ -93,6 +93,7 @@ Cors__AllowedOrigins=${cors_origin} TZ=Europe/Paris REDIS_PASSWORD=$(openssl rand -hex 32) HEIMDALL_DATA_VOLUME=heimdall_heimdall_data +PLATE_OCR_ENABLED=false EOF chmod 600 "$env_path" else @@ -118,6 +119,7 @@ else ensure_env_value TZ Europe/Paris ensure_env_value REDIS_PASSWORD "$(openssl rand -hex 32)" ensure_env_value HEIMDALL_DATA_VOLUME heimdall_heimdall_data + ensure_env_value PLATE_OCR_ENABLED false chmod 600 "$env_path" fi @@ -159,6 +161,7 @@ services: ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT} ASPNETCORE_URLS: http://+:8080 Cors__AllowedOrigins: ${Cors__AllowedOrigins} + PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false} ports: ["${WEB_PORT}:8080"] volumes: - heimdall_data:/var/lib/heimdall diff --git a/skills/deployment-guide-acceptance/SKILL.md b/skills/deployment-guide-acceptance/SKILL.md new file mode 100644 index 0000000..eca20a1 --- /dev/null +++ b/skills/deployment-guide-acceptance/SKILL.md @@ -0,0 +1,31 @@ +--- +name: deployment-guide-acceptance +description: Keep Heimdall's Docker installation and backup guides aligned with the actual Compose assets and validate source-built installation flows in a disposable project. +--- + +# Heimdall deployment guide acceptance + +Read `AGENTS.md`, `todo.md`, `docs/docker-compose.md`, and the relevant Compose and focused skills before changing deployment instructions. + +## Project-specific documentation checks + +- Central production is PostgreSQL plus Heimdall Web. The development Compose builds Central from source; the interactive Linux/Windows installers create deployment files without cloning the repository. +- Production Agent Compose is generated in Central for the selected site and pins the image digest. The repository's Agent Compose files are development or optional hardware overlays only. +- Recording quota is configured through `RECORDING_STORAGE_QUOTA_MAX_BYTES`; absent an override, Central uses 1 TiB. +- The Central image installs Tesseract plus English language data. `PLATE_OCR_ENABLED` is mapped to `PlateOcr__Enabled` by the development and production Compose files and both Linux/Windows installer templates. New installs default it to false; upgrades preserve an existing value and add false if absent. If documented, explain that OCR is an operator-uploaded crop processed locally, not automatic video detection or face recognition; mention temporary crop deletion and that OCR candidates do not establish identity. +- The scheduled backup service installs AWS CLI, Bash, and GNU coreutils. The backup scripts select AWS CLI in this image and use S3-compatible configuration; do not instruct operators to download the retired MinIO `mc` URL. +- Optional Compose projects depend on the documented external core network and, where stated, the Central data volume. Do not describe an optional service as part of required startup. + +## Disposable installation acceptance + +1. Follow the local development installation commands in `docs/docker-compose.md` from the changed checkout. Create a unique project, isolated bridge, generated database/JWT credentials and unused loopback ports under a temporary directory. Do not copy production `.env`, use the default credentials unchanged, or use deployed volumes/networks. +2. Run Compose config validation, build Central from source, start PostgreSQL and Central, then verify PostgreSQL health, Central `/healthz`, bootstrap status, and the documented opt-in default for OCR. +3. When documentation covers OCR enablement, set `PLATE_OCR_ENABLED=true` in the generated temporary env and verify the option reaches the container, then exercise the synthetic crop path. Also verify false by default. Do not infer real camera accuracy. +4. Tear down only the named project with `down --volumes --remove-orphans`; verify zero project containers, volumes, and networks. Remove temporary environment and secret files. +5. Keep Windows installer execution, production recovery, external S3 services, and real hardware acceptance open unless independently run on those targets. + +When the Docker daemon is reserved by another acceptance, perform static source/config review and record the Compose run as pending. Never launch an overlapping project to satisfy this recipe. + +## Latest local attempt + +On 5 November 2026, Compose configuration and installer-source assertions passed, but the source build acceptance did not complete: BuildKit's docker-buildx client remained blocked for over eight minutes after its compiler child disappeared, with no project containers created. The command was interrupted; its cleanup trap confirmed zero project containers, volumes, and networks and removed the generated env. A follow-up Compose project hmd-ocr-env-safe-1793874420 reused the previously source-built Central OCR image (the current checkout rebuild was still blocked) to exercise the changed Compose wiring: default PlateOcr__Enabled=false and explicit true after recreate both reported healthy. Sentry__Dsn was explicitly empty. Cleanup verified zero containers, volumes, and networks. An earlier attempt without the Sentry override emitted synthetic EF log events to the configured GlitchTip; no real credentials/data were used. The Compose environment mapping is verified; rebuilding this exact checkout and Windows installer execution remain unverified. pwsh was not installed, so the Windows installer was reviewed statically only. diff --git a/todo.md b/todo.md index ede68d8..a24b91b 100644 --- a/todo.md +++ b/todo.md @@ -33,9 +33,9 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. - [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. - [ ] **AGENT-08** Le Central simulé par Kestrel sert une configuration une seule fois; l’Agent applique une fois son snapshot, envoie deux ACK avec le même digest après un HTTP 503, puis Central persiste exactement un ACK avec HTTP 204. Test ciblé 1/1 et suite Agent 399/399 réussis localement. La recette Compose isolée construite depuis les dépendances source avec SDK 10.0.100 a exécuté le test Kestrel : configuration GET une fois, ACK même digest après 503 puis 204, application snapshot une fois, résultat 1/1. Le projet `hmdack_8df77197` a été démonté; conteneurs, volumes, réseau et source temporaire vérifiés/supprimés à 0. La validation sur Agent/caméra réels et coupure réseau reste ouverte. -- [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. -- [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. -- [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. +- [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Validation simulée locale ajoutée le 5 novembre 2026 : tests ciblés SnapshotPipelineServiceTests, CameraStreamServiceTests, FrameAnalyzerServiceTests, PipelineDegradationManagerTests et FrameAnalyzerDegradationTests passent 88/88; couvre démarrages/arrêts répétés, arrêt de flux et nettoyage, saturation/rejets, dégradation/récupération. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. +- [ ] **AGENT-10** Validation simulée locale le 5 novembre 2026 : les tests Agent ciblés passent 88/88 sur cycles start/stop, arrêts/répétitions et nettoyage du pipeline; ils ne simulent pas une charge soutenue ni une contrainte mémoire/CPU/disque complète. Restent la charge/restart/arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. +- [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Tests simulés Agent du 5 novembre (88/88 au total) couvrent start/stop répétés et nettoyage des flux; ils ne prouvent pas les délais OFF/ON ni persistance après reboot. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. - [x] **Accès caméra #141** Les PR #65/#88/#100 valident API, remplacement UI atomique, chargement paginé, protection du brouillon et révocation des grants excédentaires (>500). Validation complétée sur la branche de clôture : `ResourceAccessTests` vérifie l’union direct + groupe et la révocation live; `HttpIsolationTests` exerce le pipeline HTTP avec périmètres; un test bUnit `GroupsPage_GererAccesCamera_AfficheSiteEtAccordePuisRetireLaCamera` vérifie l’affichage site/caméra et les appels d’ajout/retrait depuis l’UI. Les tests couvrent les priorités d’accès dans l’interface et la révocation; aucune caméra physique n’est requise pour cette gestion des autorisations. Skill dédiée : `skills/camera-access-groups/SKILL.md`. - [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel. - [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Le 5 novembre 2026, le projet `hmdbk_a466d0ce` a vérifié le dump S3 daté, `latest.sql.gz`, sa restauration avec retour de `after-backup` à `before-restore`, l’upload protégé et le miroir RustFS/manifest. La recette a aussi révélé que l’ancien téléchargement de `mc` échouait en HTTP 410 et que BusyBox `date` ne calculait pas les seuils relatifs; Compose installe maintenant AWS CLI, Bash et GNU coreutils, et chaque appel AWS reçoit les clés configurées. Une nouvelle acceptance depuis `docker/docker-compose.backup.yml` + overlay jetable a vérifié le roundtrip PostgreSQL `after-backup`→`before-restore`, la purge de clés journalières et hebdomadaires anciennes, le manifeste RustFS et l’upload protégé; teardown vérifié à 0 conteneur/volume/réseau. Les mesures RPO/RTO sur installation/données réelles restent externes. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. @@ -47,16 +47,16 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. -- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut, limites fichier/dimensions/délai et suppression du crop temporaire. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. +- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. L’acceptation Agent n’est pas concluante: les `docker create` de `agent-state-init` sont restés bloqués/ont fait conflit dans le daemon partagé; aucun Agent GPU n’a démarré, donc pas de preuve healthz/enregistrement/inférence CPU dans cette image. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent l’acceptation complète de l’Agent CUDA sans device (inscription, frame synthétique et inférence CPU effective), puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. -- [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` à revérifier après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. +- [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` repassé le 5 novembre après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. - [x] **UI groupes #138 / accès #134** L’éditeur permet de parcourir les comptes par nom/e-mail, de lister et retirer les membres, et d’accorder/révoquer les accès caméra avec nom de caméra et site. Le 4 novembre 2026, la revue a trouvé puis corrigé le POST membre qui visait une route inexistante; le client utilise désormais `POST /api/groups/{groupId}/users/{userId}` et `GET /api/groups/{groupId}/users`. Vérifications : Web groupes + client API 39/39; matrice d’autorisation Web 14/14; CameraAccessService Infrastructure 25/25; scénario PostgreSQL relationnel 1/1 valide l’union direct/groupe, le maintien du droit restant après révocation de l’autre, puis l’arrêt du grant d’un groupe supprimé. Recette Compose source jetable : bootstrap Admin, création groupe, ajout/liste/retrait membre et liste vide, tous HTTP 200; conteneurs, volumes, réseau et secrets temporaires vérifiés supprimés. Skill : `skills/group-access/SKILL.md`. - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. -- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; reste une validation de scraping sur un déploiement et l'évolution réelle des mesures. +- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); aucun test Web ne scrappe actuellement /metrics. Restent scraping de bout en bout sur déploiement et évolution réelle des mesures. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. -- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Restent la validation des seuils sur déploiement et les pannes à valider sur déploiement réel. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. -- [ ] Actualiser les guides après chaque changement d'infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Vérifier une installation depuis la documentation. +- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Les tests HealthController PostgreSQL et l'échec réseau/stockage réel ne sont pas relancés dans cette passe; aucun test Web ne scrappe /metrics. Restent le scraping et les pannes/seuils en déploiement réel. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. +- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, et corrige les indications backup obsolètes sur mc. Vérifications statiques : bash -n scripts/install/backup, mappings YAML, sources installateurs et git diff --check passés. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir skills/deployment-guide-acceptance/SKILL.md. ## Corrections déjà livrées à préserver -- 2.54.1 From bc6eb5317025a38b7ef0cdd4aab344bbcfd3fc09 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 11:32:56 +0100 Subject: [PATCH 18/40] docs: record local metrics scrape acceptance --- skills/server-healthchecks/SKILL.md | 6 ++++++ todo.md | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/skills/server-healthchecks/SKILL.md b/skills/server-healthchecks/SKILL.md index fe1676e..97a30b7 100644 --- a/skills/server-healthchecks/SKILL.md +++ b/skills/server-healthchecks/SKILL.md @@ -11,3 +11,9 @@ Use this workflow when changing `Dockerfile` health checks, Central Compose heal - In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD. - Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required. - For acceptance, build the changed Central or Agent image from source in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy and remove only that project with `down --volumes --remove-orphans`. Verify no labeled containers, volumes, or networks remain. + +## Metrics scrape acceptance + +For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. + +On 5 November 2026, project hmd-metrics-scrape-1793874584 used the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This local check does not validate a deployed Prometheus server or alert thresholds. diff --git a/todo.md b/todo.md index a24b91b..cceb2d9 100644 --- a/todo.md +++ b/todo.md @@ -53,9 +53,9 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` repassé le 5 novembre après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. - [x] **UI groupes #138 / accès #134** L’éditeur permet de parcourir les comptes par nom/e-mail, de lister et retirer les membres, et d’accorder/révoquer les accès caméra avec nom de caméra et site. Le 4 novembre 2026, la revue a trouvé puis corrigé le POST membre qui visait une route inexistante; le client utilise désormais `POST /api/groups/{groupId}/users/{userId}` et `GET /api/groups/{groupId}/users`. Vérifications : Web groupes + client API 39/39; matrice d’autorisation Web 14/14; CameraAccessService Infrastructure 25/25; scénario PostgreSQL relationnel 1/1 valide l’union direct/groupe, le maintien du droit restant après révocation de l’autre, puis l’arrêt du grant d’un groupe supprimé. Recette Compose source jetable : bootstrap Admin, création groupe, ajout/liste/retrait membre et liste vide, tous HTTP 200; conteneurs, volumes, réseau et secrets temporaires vérifiés supprimés. Skill : `skills/group-access/SKILL.md`. - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. -- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); aucun test Web ne scrappe actuellement /metrics. Restent scraping de bout en bout sur déploiement et évolution réelle des mesures. +- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. -- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Les tests HealthController PostgreSQL et l'échec réseau/stockage réel ne sont pas relancés dans cette passe; aucun test Web ne scrappe /metrics. Restent le scraping et les pannes/seuils en déploiement réel. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. +- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Les tests HealthController PostgreSQL et l'échec réseau/stockage réel ne sont pas relancés dans cette passe; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent HealthController PostgreSQL ciblé, scrape Prometheus déployé et pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. - [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, et corrige les indications backup obsolètes sur mc. Vérifications statiques : bash -n scripts/install/backup, mappings YAML, sources installateurs et git diff --check passés. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir skills/deployment-guide-acceptance/SKILL.md. ## Corrections déjà livrées à préserver -- 2.54.1 From 7d741637f3e81f73ed1064659fae54f2e990424b Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 11:38:35 +0100 Subject: [PATCH 19/40] docs: record readiness and OCR UI validation --- skills/server-healthchecks/SKILL.md | 2 ++ skills/vision-identity/SKILL.md | 2 +- todo.md | 4 ++-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/skills/server-healthchecks/SKILL.md b/skills/server-healthchecks/SKILL.md index 97a30b7..b01199b 100644 --- a/skills/server-healthchecks/SKILL.md +++ b/skills/server-healthchecks/SKILL.md @@ -17,3 +17,5 @@ Use this workflow when changing `Dockerfile` health checks, Central Compose heal For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. On 5 November 2026, project hmd-metrics-scrape-1793874584 used the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This local check does not validate a deployed Prometheus server or alert thresholds. + +PostgreSQL readiness regression checks were also rerun locally on 5 November 2026: HealthControllerTests passed 5/5 with the disposable Testcontainers database. The Testcontainers reaper and database stopped after the run; unrelated labeled database services were left untouched. diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md index 62de39e..4fe063f 100644 --- a/skills/vision-identity/SKILL.md +++ b/skills/vision-identity/SKILL.md @@ -32,7 +32,7 @@ Official sources reviewed: ## Acceptance -1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test. +1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test. 2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. 3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing. 4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. diff --git a/todo.md b/todo.md index cceb2d9..a614aeb 100644 --- a/todo.md +++ b/todo.md @@ -47,7 +47,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. -- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 5/5, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. +- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. L’acceptation Agent n’est pas concluante: les `docker create` de `agent-state-init` sont restés bloqués/ont fait conflit dans le daemon partagé; aucun Agent GPU n’a démarré, donc pas de preuve healthz/enregistrement/inférence CPU dans cette image. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent l’acceptation complète de l’Agent CUDA sans device (inscription, frame synthétique et inférence CPU effective), puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` repassé le 5 novembre après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. @@ -55,7 +55,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Localisation #142** Le shell, le tableau de bord, le profil et les pages/composants UI utilisent les ressources FR/EN, avec français par défaut, bascule sans rechargement et clés complètes. Les notifications d’événements, les digests, les emails d’inscription/réinitialisation et le test SMTP utilisent aussi les ressources serveur FR/EN. La CI PR #93 (run #303) a passé le build, les suites .NET (1 730 tests), les 34 tests E2E, le contrôle NuGet et les builds/scans des images serveur et Agent. - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. -- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Les tests HealthController PostgreSQL et l'échec réseau/stockage réel ne sont pas relancés dans cette passe; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent HealthController PostgreSQL ciblé, scrape Prometheus déployé et pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. +- [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Le test ciblé HealthControllerTests PostgreSQL est repassé 5/5 le 5 novembre; l’échec réseau/stockage réel reste non validé; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent le scrape Prometheus déployé et les pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. - [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, et corrige les indications backup obsolètes sur mc. Vérifications statiques : bash -n scripts/install/backup, mappings YAML, sources installateurs et git diff --check passés. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir skills/deployment-guide-acceptance/SKILL.md. ## Corrections déjà livrées à préserver -- 2.54.1 From d881ee152b25bfa1ce6962cb692df79d69af89cd Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 11:48:50 +0100 Subject: [PATCH 20/40] docs: clean recipe-built images after acceptance --- AGENTS.md | 2 +- skills/agent-runtime-acceptance/SKILL.md | 2 ++ skills/backup-restore/SKILL.md | 2 ++ skills/camera-access-groups/SKILL.md | 1 + skills/central-auto-updates/SKILL.md | 2 ++ skills/compose-disposable-recipe/SKILL.md | 23 +++++++++++++++------ skills/deployment-guide-acceptance/SKILL.md | 3 ++- skills/first-admin-bootstrap/SKILL.md | 1 + skills/gpu-inference/SKILL.md | 1 + skills/group-access/SKILL.md | 4 +++- skills/heimdall-identity/SKILL.md | 1 + skills/mdns-camera-discovery/SKILL.md | 2 ++ skills/pwa/SKILL.md | 1 + skills/renovate-automation/SKILL.md | 1 + skills/server-healthchecks/SKILL.md | 4 ++-- skills/video-recording/SKILL.md | 1 + skills/vision-identity/SKILL.md | 3 ++- skills/webrtc-live/SKILL.md | 4 +++- todo.md | 2 +- 19 files changed, 46 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 59df025..7a87cae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # Heimdall contributor rules - For every feature, fix, operational change, or meaningful documentation change, create or update a focused skill under `skills/` in the same PR. The skill must capture the project-specific implementation and acceptance workflow, not restate generic guidance. -- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, and project names; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes are gone. Do not skip this recipe silently when Docker is unavailable. +- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, project names, and unique tags for locally built acceptance images; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes/networks are gone, then remove and verify absence of only the exact image tags built by that recipe. Keep shared upstream/base images. Never use broad image pruning. Do not skip this recipe silently when Docker is unavailable. - Read `todo.md` before changing code. Update its status and acceptance notes in the same PR as each correction or feature. Remove a completed item only after the behavior is verified; keep a short completion entry for traceability. - Keep `Domain` independent of infrastructure. Put use cases and interfaces in `Application`, adapters and EF Core persistence in `Infrastructure`, HTTP/UI composition in `Web`, and camera/runtime behavior in `Agent`. - Target the SDK pinned by `global.json` and .NET 10 or newer. Use nullable reference types, cancellation tokens for I/O, and explicit options validation. Do not weaken locked restore or suppress a new warning without a reason. diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index 0a77a66..97171ca 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -24,6 +24,8 @@ dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. Tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source. Serialize Docker acceptance when another source build is using the shared daemon. +This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`. + ## Acceptance boundary In-memory SignalR/HTTP fixtures and a local Agent container validate reconnect and runtime behavior without a physical camera. Mark real-camera stream stability, resource release on the deployed host, and LAN discovery as open until they pass on representative hardware and network equipment. diff --git a/skills/backup-restore/SKILL.md b/skills/backup-restore/SKILL.md index 9236691..29f0a1b 100644 --- a/skills/backup-restore/SKILL.md +++ b/skills/backup-restore/SKILL.md @@ -24,3 +24,5 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res 6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox). Do not rely on the retired MinIO client download URL. The scripts pass configured S3 credentials explicitly to AWS CLI for each invocation. 7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed. 8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data. + +These backup recipes use shared upstream PostgreSQL/RustFS images and do not build a Heimdall image by default; retain those base images. If a changed recipe adds any local build, tag it uniquely for the Compose project and remove/verify that exact tag after teardown. Do not use image-prune commands. diff --git a/skills/camera-access-groups/SKILL.md b/skills/camera-access-groups/SKILL.md index 2a5ac30..7d2e0d7 100644 --- a/skills/camera-access-groups/SKILL.md +++ b/skills/camera-access-groups/SKILL.md @@ -16,5 +16,6 @@ When changing this area, verify: - `GroupsPageTests` for site/camera labels and the UI add/remove request sequence. - PostgreSQL integration tests for persistence or query changes; do not use EF InMemory as relational proof. - The disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md` for behavior or deployment changes, using a unique project, network, credentials, ports, and volumes. +- If Compose builds Central from source, override its image with a project-unique tag and remove/verify that exact tag after teardown; retain shared base images. Use synthetic camera metadata in automated tests. Physical RTSP, snapshot and reconnect behavior is a separate Agent/camera acceptance and must be reported as unverified unless run against real hardware. diff --git a/skills/central-auto-updates/SKILL.md b/skills/central-auto-updates/SKILL.md index 76d49be..48d6ef1 100644 --- a/skills/central-auto-updates/SKILL.md +++ b/skills/central-auto-updates/SKILL.md @@ -36,3 +36,5 @@ Use this skill when changing the Linux or Windows Central installer, its generat ## Acceptance Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and scoped teardown. Never connect the recipe to a deployed Docker daemon or production data. + +If acceptance builds a local Central image, assign a project-unique tag and remove/verify that tag after teardown. Do not remove registry/base images or use broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup. diff --git a/skills/compose-disposable-recipe/SKILL.md b/skills/compose-disposable-recipe/SKILL.md index 276c559..6acea23 100644 --- a/skills/compose-disposable-recipe/SKILL.md +++ b/skills/compose-disposable-recipe/SKILL.md @@ -12,15 +12,26 @@ Use this skill for every Heimdall behavior, deployment, or operational change. R - Build from the current source with a unique Compose project name. Do not test against the production hostname, database, image volumes, secrets, or credentials. - Put generated `.env` and secret files under a temporary directory outside the repository. Use synthetic test identities and cryptographically random local passwords. - Use an unused loopback host port and Compose-managed volumes whose names include the unique project name. Do not join production or shared networks. -- Never use broad Docker cleanup such as `docker system prune`. Remove only the test project with `docker compose -p down --volumes --remove-orphans`. -- After cleanup, check that the test project has no containers or volumes. Remove its temporary files and keep logs free of credentials. +- Give each locally built acceptance image a project-unique tag, for example `heimdall:-acceptance`; do not build under `latest`, `local`, or a tag that existed before the recipe. Use a temporary Compose override to set the unique image tag while preserving the source build context. Record all generated tags before starting. +- Never use broad Docker cleanup such as `docker system prune`, `docker image prune`, or `docker rmi $(docker images -q)`. Remove only the test project with `docker compose -p down --volumes --remove-orphans`. +- After teardown, check that the project has no containers, volumes, or networks. For every locally built image tag, run `docker image rm ` if it exists, then verify `docker image inspect ` fails. Remove the temporary Compose override/env/source files. Do not remove shared upstream base images (for example PostgreSQL, .NET SDK, or MediaMTX) or images owned by another recipe/project. +- Put teardown and exact-tag image removal in the same cleanup trap so both success and failure paths clean up. Do not reuse another acceptance recipe's locally built image: build a uniquely tagged image for this recipe and remove it in this recipe's cleanup path. ## Acceptance workflow 1. Inspect the Compose file and interpolation requirements before starting it. Generate a temporary environment file with unique database/JWT secrets and a distinct loopback port. -2. Start the minimal Central + PostgreSQL stack from source with `docker compose -p --env-file -f docker/docker-compose.yml up -d --build`. -3. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path. -4. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files. -5. Tear down the named project and its volumes in a cleanup path. Verify removal and delete temporary files. +2. Generate a temporary Compose image override. For example: + + ```yaml + services: + heimdall: + image: heimdall:${ACCEPTANCE_PROJECT}-central + ``` + + Put `ACCEPTANCE_PROJECT=` in the temporary env file and include both Compose files in every command. This overrides only the image tag; the checked-in source build context is retained. Use similarly unique tags for any Agent or helper image built from this checkout. +3. Start the minimal Central + PostgreSQL stack from source with `docker compose -p --env-file -f docker/docker-compose.yml -f up -d --build`. +4. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path. +5. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files. +6. Tear down the named project and its volumes in a cleanup path. Verify no project containers, volumes, or networks remain. Remove every project-unique image tag created by this recipe and verify it is absent; retain only shared upstream/base images. Delete temporary environment and secret files. If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed. diff --git a/skills/deployment-guide-acceptance/SKILL.md b/skills/deployment-guide-acceptance/SKILL.md index eca20a1..8c6898d 100644 --- a/skills/deployment-guide-acceptance/SKILL.md +++ b/skills/deployment-guide-acceptance/SKILL.md @@ -22,7 +22,8 @@ Read `AGENTS.md`, `todo.md`, `docs/docker-compose.md`, and the relevant Compose 2. Run Compose config validation, build Central from source, start PostgreSQL and Central, then verify PostgreSQL health, Central `/healthz`, bootstrap status, and the documented opt-in default for OCR. 3. When documentation covers OCR enablement, set `PLATE_OCR_ENABLED=true` in the generated temporary env and verify the option reaches the container, then exercise the synthetic crop path. Also verify false by default. Do not infer real camera accuracy. 4. Tear down only the named project with `down --volumes --remove-orphans`; verify zero project containers, volumes, and networks. Remove temporary environment and secret files. -5. Keep Windows installer execution, production recovery, external S3 services, and real hardware acceptance open unless independently run on those targets. +5. Assign the locally built Central image a unique tag containing the project name. After teardown, remove and verify absence of that exact tag. Keep shared upstream runtime/database images and never prune images broadly. +6. Keep Windows installer execution, production recovery, external S3 services, and real hardware acceptance open unless independently run on those targets. When the Docker daemon is reserved by another acceptance, perform static source/config review and record the Compose run as pending. Never launch an overlapping project to satisfy this recipe. diff --git a/skills/first-admin-bootstrap/SKILL.md b/skills/first-admin-bootstrap/SKILL.md index 447caf7..6790be6 100644 --- a/skills/first-admin-bootstrap/SKILL.md +++ b/skills/first-admin-bootstrap/SKILL.md @@ -13,5 +13,6 @@ Use this skill when changing account bootstrap, signup, login routing, user crea - Existing installations with users skip setup and keep their accounts. The bootstrap flow must not overwrite or replace existing users. - Update FR/EN resources, route behavior, API client behavior, and tests together. Remove public registration links and ensure direct calls to the old registration route are rejected after setup. - For every implementation change, follow `compose-disposable-recipe` and validate both an empty database (setup and first admin) and an initialized database (setup closed, anonymous registration rejected, admin account creation available). +- Tag every source-built Central image with the unique Compose project name and remove/verify that exact tag after teardown; retain shared PostgreSQL and .NET base images. Never use credentials supplied for a real deployment in tests. Use generated credentials in the disposable Compose environment and sanitize logs. diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index cbf77a3..35b76bc 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -22,6 +22,7 @@ Use this skill when changing ONNX Runtime packages, execution provider configura - Add tests for CPU-only selection, successful CUDA selection, missing CUDA provider, and CUDA session initialization failure. Also exercise the repository YOLO fixture with the CPU provider so package changes preserve real inference. - Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output. - Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution. +- Tag the locally built CUDA Agent and any Central fixture image with the unique acceptance project name. After stopping the project, remove those exact tags and verify they are absent; retain shared CUDA/runtime base layers and never use `docker image prune`. - The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; the dev overlay targets `linux/amd64` and the Dockerfile uses that target rather than a constant `FROM --platform` override. Refresh the digest only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest. diff --git a/skills/group-access/SKILL.md b/skills/group-access/SKILL.md index f37d601..f077af8 100644 --- a/skills/group-access/SKILL.md +++ b/skills/group-access/SKILL.md @@ -30,5 +30,7 @@ grant. Soft-deleted groups must stop granting access immediately. list, remove the member, and verify the empty list. Use only synthetic data. 3. Tear down that exact project with volumes and orphans, verify there are no project containers, volumes, or networks, and delete generated secret files. -4. Update `todo.md` with the exact evidence and keep physical/deployment-only +4. Remove and verify absence of every project-unique locally built image tag + after teardown. Retain shared upstream PostgreSQL/.NET runtime images. +5. Update `todo.md` with the exact evidence and keep physical/deployment-only claims separate from local acceptance. diff --git a/skills/heimdall-identity/SKILL.md b/skills/heimdall-identity/SKILL.md index 08213d9..c35211c 100644 --- a/skills/heimdall-identity/SKILL.md +++ b/skills/heimdall-identity/SKILL.md @@ -25,5 +25,6 @@ Read `AGENTS.md`, the `AUTH-BOOTSTRAP` entry in `todo.md`, and the Identity wiri - Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility. - For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update `todo.md`, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network. - Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked. +- Give each source-built Central acceptance image a project-unique tag; remove and verify absence of that exact tag after Compose teardown. Keep shared upstream base images and avoid all broad image-prune commands. Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction). diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md index 6194955..34108b8 100644 --- a/skills/mdns-camera-discovery/SKILL.md +++ b/skills/mdns-camera-discovery/SKILL.md @@ -25,3 +25,5 @@ Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL ## Disposable Compose Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. + +This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`. diff --git a/skills/pwa/SKILL.md b/skills/pwa/SKILL.md index 7db16e1..19c80b4 100644 --- a/skills/pwa/SKILL.md +++ b/skills/pwa/SKILL.md @@ -19,5 +19,6 @@ The supported PWA deployment is at the web origin root (`/`). The Blazor app use 1. Run `tests/Heimdall.E2E.Tests` with its disposable PostgreSQL fixture and Chromium. Check unauthenticated manifest and icon access, exact public-shell contents, offline navigation fallback, and absence of cached private content. 2. Build the changed source through the disposable Central + PostgreSQL Compose recipe in `skills/compose-disposable-recipe/SKILL.md`; probe `/healthz`, `/manifest.webmanifest`, `/service-worker.js` and the offline page. Use unique project/ports/credentials/volumes and verify teardown. + Assign the locally built Central image a project-unique tag; remove and verify that exact tag after teardown, while retaining shared .NET/PostgreSQL bases. 3. Review `docs/pwa.md` and deployment instructions for HTTPS, root hosting, reverse proxy/WebSocket support, update and rollback behavior. Report physical iOS/Android/desktop installation, HTTPS proxy, and mobile sleep/network testing only when run on those real environments. 4. Keep the PWA backlog open for validations that require real browsers/devices or remote push infrastructure. Do not claim Web Push exists without a tested VAPID backend, subscriptions, revocation and permission-aware delivery. diff --git a/skills/renovate-automation/SKILL.md b/skills/renovate-automation/SKILL.md index 3a3f21b..3ac2af1 100644 --- a/skills/renovate-automation/SKILL.md +++ b/skills/renovate-automation/SKILL.md @@ -12,4 +12,5 @@ Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependen - HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR. - Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials. - For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Remove that exact project and confirm it leaves no containers or volumes; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored. +- The mock-preflight recipe uses a shared upstream Node image and creates no local application image. Retain that base image; if the recipe adds a local build, use a project-unique tag and remove/verify only that exact tag after teardown. - For operational changes, update the P0 Renovate status in `todo.md` with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence. diff --git a/skills/server-healthchecks/SKILL.md b/skills/server-healthchecks/SKILL.md index b01199b..76eed22 100644 --- a/skills/server-healthchecks/SKILL.md +++ b/skills/server-healthchecks/SKILL.md @@ -10,11 +10,11 @@ Use this workflow when changing `Dockerfile` health checks, Central Compose heal - Central and Agent containers probe `/healthz` on port 8080 (the development Agent may bind its host-mapped port). ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy. - In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD. - Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required. -- For acceptance, build the changed Central or Agent image from source in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy and remove only that project with `down --volumes --remove-orphans`. Verify no labeled containers, volumes, or networks remain. +- For acceptance, build the changed Central or Agent image from source under a project-unique tag in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy and remove only that project with `down --volumes --remove-orphans`. Verify no labeled containers, volumes, or networks remain, remove and inspect the exact local image tag, and retain shared base images. ## Metrics scrape acceptance -For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. +For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. Remove and verify absence of that recipe's unique server image tag afterward. On 5 November 2026, project hmd-metrics-scrape-1793874584 used the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This local check does not validate a deployed Prometheus server or alert thresholds. diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index ad0d940..ba9d487 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -16,5 +16,6 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. - For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. - For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. +- For each recording recipe, use project-unique tags for locally built Central and Agent images, then remove and verify those exact tags after Compose teardown. Retain shared PostgreSQL/MediaMTX base images. Follow `skills/compose-disposable-recipe/SKILL.md`; never use `image prune`. Current product gaps are audio/event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md index 4fe063f..307cdb1 100644 --- a/skills/vision-identity/SKILL.md +++ b/skills/vision-identity/SKILL.md @@ -36,4 +36,5 @@ Official sources reviewed: 2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. 3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing. 4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. -5. This acceptance covers one clean synthetic crop and API persistence only. It does not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or event retention/privacy suitability. +5. Give the source-built Central image a unique tag containing the Compose project name; remove and verify that exact tag after `down`. The historical acceptance image tags from this recipe have been removed. Retain the shared .NET/ASP.NET base images and never use broad image pruning. +6. This acceptance covers one clean synthetic crop and API persistence only. It does not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or event retention/privacy suitability. diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md index 27070c4..d093eb4 100644 --- a/skills/webrtc-live/SKILL.md +++ b/skills/webrtc-live/SKILL.md @@ -67,6 +67,8 @@ the Agent. Configure its assigned camera against the host loopback RTSP port. Do 5. Logs and API errors contain no credentials, raw tokens, RTSP URLs, or ICE secrets. Verify configured ICE/TURN candidate behavior separately. 6. Tear down only that Compose project with volumes/orphans, then verify its - containers, volumes and network are gone. + containers, volumes and network are gone. Remove and verify absence of the + project-unique Central and Agent image tags built by this recipe. Keep the + shared MediaMTX base image; do not run image-prune commands. Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and the Agent relay test (1/1) pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Physical camera, LAN and external TURN are unvalidated; audio/PTZ remain out of scope, so keep FEAT-01 open. diff --git a/todo.md b/todo.md index a614aeb..257fcd9 100644 --- a/todo.md +++ b/todo.md @@ -56,7 +56,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Le test ciblé HealthControllerTests PostgreSQL est repassé 5/5 le 5 novembre; l’échec réseau/stockage réel reste non validé; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent le scrape Prometheus déployé et les pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. -- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, et corrige les indications backup obsolètes sur mc. Vérifications statiques : bash -n scripts/install/backup, mappings YAML, sources installateurs et git diff --check passés. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir skills/deployment-guide-acceptance/SKILL.md. +- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Onze anciens tags d’acceptance ont été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques : bash -n scripts/install/backup, mappings YAML, sources installateurs et git diff --check passés. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir skills/deployment-guide-acceptance/SKILL.md. ## Corrections déjà livrées à préserver -- 2.54.1 From 119ea0f568faa67befc23186897ab850720a7af4 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 12:18:17 +0100 Subject: [PATCH 21/40] test: cover agent update rollback and recording retries --- scripts/ci/check-efcore-usage.py | 1 + scripts/ci/test_ci.py | 30 +++++++ skills/agent-update-acceptance/SKILL.md | 22 +++++ skills/ef-core-persistence/SKILL.md | 1 + skills/gpu-inference/SKILL.md | 2 +- skills/video-recording/SKILL.md | 1 + .../AgentRecordingServiceTests.cs | 82 +++++++++++++++++++ todo.md | 6 +- 8 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 skills/agent-update-acceptance/SKILL.md diff --git a/scripts/ci/check-efcore-usage.py b/scripts/ci/check-efcore-usage.py index 284f90b..7f3995d 100644 --- a/scripts/ci/check-efcore-usage.py +++ b/scripts/ci/check-efcore-usage.py @@ -13,6 +13,7 @@ EF_CORE_EXCEPTIONS = { "src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs": "PostgreSQL VACUUM/REINDEX and catalog inspection", "src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs": "PostgreSQL partition DDL and catalog inspection", "src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs": "transaction-scoped PostgreSQL advisory lock", + "src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs": "transaction-scoped PostgreSQL advisory lock for serialized recording quota checks", "src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs": "idempotent PostgreSQL bulk insert with ON CONFLICT DO NOTHING", "src/Heimdall.Agent/Data/AgentOutboxDatabaseInitializer.cs": "baseline and migrate pre-EF local SQLite outbox schemas", } diff --git a/scripts/ci/test_ci.py b/scripts/ci/test_ci.py index 57aa9d9..9740544 100644 --- a/scripts/ci/test_ci.py +++ b/scripts/ci/test_ci.py @@ -103,6 +103,36 @@ class GpuAgentImageTests(unittest.TestCase): state_init = compose.split(' agent-state-init:', 1)[1] self.assertIn('dockerfile: docker/Dockerfile.agent.gpu', state_init) +class NativeAgentUpdateTests(unittest.TestCase): + def test_supervisor_rolls_back_failed_startup_to_previous_release(self): + with tempfile.TemporaryDirectory(prefix='hmd-supervisor-test-') as temporary: + root = Path(temporary) + old_release = root/'releases'/'v1.0.0' + new_release = root/'releases'/'v1.0.1' + old_release.mkdir(parents=True) + new_release.mkdir() + (old_release/'Heimdall.Agent.dll').write_bytes(b'old synthetic release') + (new_release/'Heimdall.Agent.dll').write_bytes(b'new synthetic release') + current = root/'current' + current.symlink_to(new_release, target_is_directory=True) + pending = root/'pending-update.json' + pending.write_text(json.dumps({'version': '1.0.1', 'previous': str(old_release)})) + dotnet = root/'fake-dotnet' + dotnet.write_text('#!/bin/sh\nexit 1\n') + dotnet.chmod(0o755) + + environment = os.environ.copy() + environment['Agent__UpdateInstallRoot'] = str(root) + environment['HEIMDALL_DOTNET'] = str(dotnet) + result = subprocess.run( + [sys.executable, str(REPO_ROOT/'install/agent-supervisor.py')], + env=environment, capture_output=True, text=True, timeout=10) + + self.assertEqual(result.returncode, 75, result.stderr) + self.assertEqual(current.resolve(), old_release.resolve()) + self.assertFalse(pending.exists()) + self.assertIn('previous release restored', result.stderr) + class AdvisoryTests(unittest.TestCase): def check(self, data): with tempfile.TemporaryDirectory() as temp: diff --git a/skills/agent-update-acceptance/SKILL.md b/skills/agent-update-acceptance/SKILL.md new file mode 100644 index 0000000..13399f3 --- /dev/null +++ b/skills/agent-update-acceptance/SKILL.md @@ -0,0 +1,22 @@ +--- +name: heimdall-agent-update-acceptance +description: Validate Heimdall native Agent install, signed update, startup health, and rollback behavior. +--- + +# Native Agent update acceptance + +Use this skill when changing `install/install-agent.sh`, `install/install-agent.ps1`, `install/agent-supervisor.py`, or `install/agent-update-supervisor.ps1`. + +## Linux rollback simulation + +- Run `python3 -m unittest discover -s scripts/ci -p 'test_*.py' -k supervisor_rolls_back_failed_startup_to_previous_release`. +- The test creates two synthetic release directories and a `current` link to the candidate, writes a pending-update marker, and injects a fake `dotnet` executable that exits immediately with failure. +- Verify the supervisor returns 75, atomically points `current` back at the prior release, removes `pending-update.json`, and reports that the previous release was restored. The fixture must live in `TemporaryDirectory` and leave no files behind. +- This covers only the startup-failure rollback branch. It does not validate HTTP update discovery, signed archive verification, a 60-second healthy startup window, systemd, Windows service behavior, or a real Agent host. + +## Local and host acceptance boundary + +- Keep `HEIMDALL_SOURCE_BASE_URL` limited to Heimdall-owned installer assets; vendor runtimes and dependencies must use their official distribution channels. +- For updates, exercise both successful and rejected signatures before installation. Preserve the previous release until the candidate has reported the expected version and stayed healthy for the configured stability interval. +- Use a temporary install root and fake runtime for local failure/rollback tests. Never point these tests at `/usr/local`, a real systemd service, production credentials, or an installed Agent state directory. +- Report Linux and Windows real-host install/update/rollback as open until each OS has been exercised with a real service and the expected signing configuration. diff --git a/skills/ef-core-persistence/SKILL.md b/skills/ef-core-persistence/SKILL.md index c93c21e..87b51c4 100644 --- a/skills/ef-core-persistence/SKILL.md +++ b/skills/ef-core-persistence/SKILL.md @@ -13,6 +13,7 @@ Use this skill whenever changing how application or Agent data is read or writte - Verify PostgreSQL translation, transaction boundaries, concurrency and deletion semantics against PostgreSQL integration tests when those behaviors matter. Do not use EF InMemory as proof of relational behavior. - Do not issue CRUD through ADO.NET or hand-written SQL. Raw SQL through EF is an exception for database-specific capabilities that LINQ cannot express or for measured performance needs. Keep it parameterized, add an adjacent `EF Core exception:` comment with the reason, and add a test for its behavior. - Migrations, test database setup, PostgreSQL maintenance/partition DDL, and locks with no portable EF equivalent are valid exceptions. Keep provider-specific code in Infrastructure or a dedicated adapter; do not spread it into use cases. +- When adding an approved raw EF operation, add its exact source path and a short capability rationale to `scripts/ci/check-efcore-usage.py`'s `EF_CORE_EXCEPTIONS` allowlist, keep an adjacent `EF Core exception:` comment, and cover the behavior with a relational test. The scanner intentionally ignores comments when locating a call; a comment alone does not allowlist a new production source. - Never enable sensitive-data logging in production. Do not log connection strings or persisted secret values. Before editing, inspect this repository's `AGENTS.md`, `todo.md`, model configuration, latest migration, and callers. After editing, run the relevant suite and CI persistence policy check, then update the corresponding TODO item with evidence and remaining deployment checks. diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index 35b76bc..3531b7a 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -28,4 +28,4 @@ Use this skill when changing ONNX Runtime packages, execution provider configura ## Current limitation -The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from source with the locked GPU package. Rendered Compose confirmed that CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A disposable Central/PostgreSQL stack passed bootstrap and `/healthz`, but Docker could not create the GPU overlay's `agent-state-init` container (stalled/conflicting create calls in the shared daemon); the Agent never started. Therefore Agent health, token registration, and an actual CPU inference from the CUDA image remain unverified. Retry the complete recipe with an available Docker daemon slot: bootstrap a disposable site, run the GPU image without NVIDIA devices, attach a synthetic RTSP source, and verify an inference observation with `CPUExecutionProvider` before teardown. The first Central attempt used a malformed synthetic Npgsql connection string and produced one GlitchTip report; the fixture was corrected and the DSN disabled for the subsequent run. It contained no production data or secrets. Physical CUDA execution also remains open. +The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from this source with locked GPU restore. Rendered Compose confirmed CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A local disposable runtime check launched the GPU image without NVIDIA devices on an isolated network and tmpfs state: logs confirmed no GPU detection, fallback to `CPUExecutionProvider`, and YOLO model initialization; a synthetic HTTP Central mock accepted registration and heartbeat (200/204), and `/healthz` returned 200. The repository `RealOnnx_CpuModel_ProcessesFullHdImage` test passed 1/1 with `HeimdallOnnxRuntime=GPU`. The mock did not implement configuration/jobs, so no camera frame traversed the Agent/Central loop; a synthetic frame and persisted inference observation remain open. The exact acceptance image tag and container were removed and verified absent; tmpfs, mock listener, and temporary state were gone. The earlier disposable Central/PostgreSQL bootstrap also passed. Physical CUDA execution still requires NVIDIA hardware. diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index ba9d487..041be9a 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -14,6 +14,7 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL. - Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance. - Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. +- `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` seeds a manifest and MP4 into a temporary spool, returns 503 then 204 from a mock Central, and proves the segment remains through failure, reuses the same idempotency URL/API-key boundary, and is deleted only after success. - For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. - For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. - For each recording recipe, use project-unique tags for locally built Central and Agent images, then remove and verify those exact tags after Compose teardown. Retain shared PostgreSQL/MediaMTX base images. Follow `skills/compose-disposable-recipe/SKILL.md`; never use `image prune`. diff --git a/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs index 3d54255..5bd5a78 100644 --- a/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs @@ -1,3 +1,9 @@ +using System.Collections.Concurrent; +using Heimdall.Agent.Services; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; + namespace Heimdall.Agent.Tests; public sealed class AgentRecordingServiceTests @@ -19,4 +25,80 @@ public sealed class AgentRecordingServiceTests info.ArgumentList.ShouldContain("/tmp/segments/segment-%06d.mp4"); info.UseShellExecute.ShouldBeFalse(); } + + [Fact] + public async Task UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity() + { + using var temp = new TempDir(); + var cameraId = Guid.NewGuid(); + var sessionId = Guid.NewGuid(); + var sessionDirectory = Path.Combine(temp.Path, "recordings", cameraId.ToString("N"), sessionId.ToString("N")); + Directory.CreateDirectory(sessionDirectory); + var segmentPath = Path.Combine(sessionDirectory, "segment-000001.mp4"); + await File.WriteAllBytesAsync(segmentPath, [0, 0, 0, 24, 102, 116, 121, 112]); + await File.WriteAllTextAsync(Path.Combine(sessionDirectory, "started-at.txt"), DateTime.UtcNow.ToString("O")); + await File.WriteAllTextAsync(Path.Combine(sessionDirectory, "segments.csv"), "segment-000001.mp4,0.000000,12.000000\n"); + + var requests = new ConcurrentQueue<(string Url, string? ApiKey, string? ContentType, bool SegmentExists)>(); + var firstResponse = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondResponse = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var requestCount = 0; + using var client = new HttpClient(new MockHttpMessageHandler(request => + { + requests.Enqueue((request.RequestUri!.ToString(), request.Headers.GetValues("X-API-Key").Single(), + request.Content?.Headers.ContentType?.MediaType, File.Exists(segmentPath))); + var status = Interlocked.Increment(ref requestCount) == 1 + ? System.Net.HttpStatusCode.ServiceUnavailable + : System.Net.HttpStatusCode.NoContent; + if (requestCount == 1) firstResponse.TrySetResult(); + else secondResponse.TrySetResult(); + return new HttpResponseMessage(status); + })) { BaseAddress = new Uri("http://central.test/") }; + var clients = Substitute.For(); + clients.CreateClient("Central").Returns(client); + var streams = new CameraStreamService(NullLogger.Instance); + var service = new AgentRecordingService(new CameraConfigStore(), streams, + new AgentState { ApiKey = "synthetic-agent-key" }, + Options.Create(new AgentOptions + { + CentralUrl = "http://central.test", + SiteToken = "synthetic-site-token", + StateDirectory = temp.Path, + RecordingSpoolMaxBytes = 16 * 1024 * 1024 + }), clients, NullLogger.Instance); + + try + { + await service.StartAsync(CancellationToken.None); + await firstResponse.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await WaitUntilAsync(() => File.Exists(segmentPath), TimeSpan.FromSeconds(2)); + await secondResponse.Task.WaitAsync(TimeSpan.FromSeconds(12)); + await WaitUntilAsync(() => !File.Exists(segmentPath), TimeSpan.FromSeconds(2)); + + requestCount.ShouldBe(2); + var attempts = requests.ToArray(); + attempts[0].Url.ShouldBe(attempts[1].Url); + attempts[0].Url.ShouldContain($"/api/cameras/{cameraId:D}/recordings/"); + attempts[0].ApiKey.ShouldBe("synthetic-agent-key"); + attempts[1].ApiKey.ShouldBe("synthetic-agent-key"); + attempts[0].ContentType.ShouldBe("video/mp4"); + attempts[1].ContentType.ShouldBe("video/mp4"); + attempts[0].SegmentExists.ShouldBeTrue(); + attempts[1].SegmentExists.ShouldBeTrue(); + File.Exists(segmentPath).ShouldBeFalse(); + } + finally + { + await service.StopAsync(CancellationToken.None); + streams.Dispose(); + } + } + + private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (!condition() && DateTime.UtcNow < deadline) + await Task.Delay(25); + condition().ShouldBeTrue(); + } } diff --git a/todo.md b/todo.md index 257fcd9..eaa0c5b 100644 --- a/todo.md +++ b/todo.md @@ -30,7 +30,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé. - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. -- [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. +- [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Simulation locale reproductible ajoutée à `scripts/ci/test_ci.py` : faux runtime candidat en échec, code superviseur 75, lien `current` restauré vers v1.0.0, marqueur de mise à jour supprimé; fixture `TemporaryDirectory` détruite automatiquement. Skill : `skills/agent-update-acceptance/SKILL.md`. Restent les validations réelles d’installation, signature, mise à jour et rollback sur hôtes Linux et Windows. - [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. - [ ] **AGENT-08** Le Central simulé par Kestrel sert une configuration une seule fois; l’Agent applique une fois son snapshot, envoie deux ACK avec le même digest après un HTTP 503, puis Central persiste exactement un ACK avec HTTP 204. Test ciblé 1/1 et suite Agent 399/399 réussis localement. La recette Compose isolée construite depuis les dépendances source avec SDK 10.0.100 a exécuté le test Kestrel : configuration GET une fois, ACK même digest après 503 puis 204, application snapshot une fois, résultat 1/1. Le projet `hmdack_8df77197` a été démonté; conteneurs, volumes, réseau et source temporaire vérifiés/supprimés à 0. La validation sur Agent/caméra réels et coupure réseau reste ouverte. - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Validation simulée locale ajoutée le 5 novembre 2026 : tests ciblés SnapshotPipelineServiceTests, CameraStreamServiceTests, FrameAnalyzerServiceTests, PipelineDegradationManagerTests et FrameAnalyzerDegradationTests passent 88/88; couvre démarrages/arrêts répétés, arrêt de flux et nettoyage, saturation/rejets, dégradation/récupération. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. @@ -46,9 +46,9 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès (2/2 tests Agent ciblés). La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. L’acceptation Agent n’est pas concluante: les `docker create` de `agent-state-init` sont restés bloqués/ont fait conflit dans le daemon partagé; aucun Agent GPU n’a démarré, donc pas de preuve healthz/enregistrement/inférence CPU dans cette image. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent l’acceptation complète de l’Agent CUDA sans device (inscription, frame synthétique et inférence CPU effective), puis l’exécution CUDA sur NVIDIA réel. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` repassé le 5 novembre après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. - [x] **UI groupes #138 / accès #134** L’éditeur permet de parcourir les comptes par nom/e-mail, de lister et retirer les membres, et d’accorder/révoquer les accès caméra avec nom de caméra et site. Le 4 novembre 2026, la revue a trouvé puis corrigé le POST membre qui visait une route inexistante; le client utilise désormais `POST /api/groups/{groupId}/users/{userId}` et `GET /api/groups/{groupId}/users`. Vérifications : Web groupes + client API 39/39; matrice d’autorisation Web 14/14; CameraAccessService Infrastructure 25/25; scénario PostgreSQL relationnel 1/1 valide l’union direct/groupe, le maintien du droit restant après révocation de l’autre, puis l’arrêt du grant d’un groupe supprimé. Recette Compose source jetable : bootstrap Admin, création groupe, ajout/liste/retrait membre et liste vide, tous HTTP 200; conteneurs, volumes, réseau et secrets temporaires vérifiés supprimés. Skill : `skills/group-access/SKILL.md`. -- 2.54.1 From 1b1b99641b99cca4d6fefb1adc75d7dd09ceaf38 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 13:10:07 +0100 Subject: [PATCH 22/40] feat: confirm OCR plate vehicle associations --- skills/compose-disposable-recipe/SKILL.md | 1 + skills/vision-identity/SKILL.md | 13 +- .../ConfirmPlateAssociationCommand.cs | 85 +++++++++++++ .../DependencyInjection.cs | 6 + .../Components/Pages/CameraDetail.razor | 103 +++++++++++++++- .../Controllers/PlateRecognitionController.cs | 23 +++- .../Localization/SharedResources.en.resx | 9 +- .../Localization/SharedResources.fr.resx | 9 +- .../Localization/SharedResources.resx | 9 +- .../Services/HeimdallApiClient.cs | 25 +++- .../ConfirmPlateAssociationHandlerTests.cs | 112 ++++++++++++++++++ .../Components/Pages/CameraDetailTests.cs | 21 ++++ .../PlateRecognitionControllerTests.cs | 3 +- todo.md | 2 +- 14 files changed, 402 insertions(+), 19 deletions(-) create mode 100644 src/Heimdall.Application/Vehicles/Commands/ConfirmPlateAssociation/ConfirmPlateAssociationCommand.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/Vehicles/ConfirmPlateAssociationHandlerTests.cs diff --git a/skills/compose-disposable-recipe/SKILL.md b/skills/compose-disposable-recipe/SKILL.md index 6acea23..5a6a02d 100644 --- a/skills/compose-disposable-recipe/SKILL.md +++ b/skills/compose-disposable-recipe/SKILL.md @@ -16,6 +16,7 @@ Use this skill for every Heimdall behavior, deployment, or operational change. R - Never use broad Docker cleanup such as `docker system prune`, `docker image prune`, or `docker rmi $(docker images -q)`. Remove only the test project with `docker compose -p down --volumes --remove-orphans`. - After teardown, check that the project has no containers, volumes, or networks. For every locally built image tag, run `docker image rm ` if it exists, then verify `docker image inspect ` fails. Remove the temporary Compose override/env/source files. Do not remove shared upstream base images (for example PostgreSQL, .NET SDK, or MediaMTX) or images owned by another recipe/project. - Put teardown and exact-tag image removal in the same cleanup trap so both success and failure paths clean up. Do not reuse another acceptance recipe's locally built image: build a uniquely tagged image for this recipe and remove it in this recipe's cleanup path. +- A recipe is not complete until every local application image tag created by that recipe has been removed and verified absent. `docker compose down` does not remove images. Apply this even when the behavioral assertion fails; keep generated upstream/base images and unrelated project images untouched. ## Acceptance workflow diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md index 307cdb1..6c2b23a 100644 --- a/skills/vision-identity/SKILL.md +++ b/skills/vision-identity/SKILL.md @@ -13,7 +13,7 @@ Read `AGENTS.md` and FEAT-03/UI-02 in `todo.md`. Current API contract only suppo - Central uses the system Tesseract executable and English LSTM data. Tesseract engine and the official `tessdata_best` model data declare Apache-2.0. Do not add other OCR or detection weights without reviewing their exact asset licenses and provenance. - The controller requires a human principal with `Camera.Write`, camera scope, JPEG/PNG signature, configured byte limit (at most 512 KiB), and rate limits. OCR rejects malformed, oversized, or over-4-megapixel crops and times out after a bounded interval. - OCR runs on the Heimdall Central host. The image is written to a random temporary path and deleted in `finally`; do not log the crop, extracted text, embedding, or raw image path. -- Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it deliberately does not persist `VehicleId`/`PersonId` links. Never treat OCR output as verified identity; a human confirmation/linking workflow is still missing. +- Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it does not persist identity links during OCR. `CameraDetail` presents the suggestion for operator review; the operator must explicitly confirm a vehicle. The confirmation API requires a human principal with both camera and vehicle write permissions, verifies access to the camera, the event-to-observation association, and an exact normalized plate match, and writes the observation/event links together. Never treat OCR output as verified identity. - OCR observations remain unassigned and use the existing cleanup that purges unassigned plate rows after 30 days. The `LicensePlateDetected` event label and metadata have no equivalent retention in this change, so event retention/privacy review remains open before enabling this in production. ## Face-model gate @@ -30,11 +30,18 @@ Official sources reviewed: - [ONNX Model Zoo sourcing and model catalog](https://github.com/onnx/models/blob/main/README.md) - [InsightFace model-zoo license statement](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md) +## Human confirmation workflow + +- Keep mismatches and ambiguous candidate lists unlinked until an operator selects a vehicle and confirms. +- Confirm with the observation ID, event ID and selected vehicle ID; reject anonymous or camera-scoped requests, mismatched plates, unrelated events, and conflicting existing links. +- Preserve the matching UI/API behavior with component/controller tests and handler tests. API authorization and camera scope stay at the Web boundary; the application handler independently checks camera access before persistence. + ## Acceptance 1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test. 2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. 3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing. 4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. -5. Give the source-built Central image a unique tag containing the Compose project name; remove and verify that exact tag after `down`. The historical acceptance image tags from this recipe have been removed. Retain the shared .NET/ASP.NET base images and never use broad image pruning. -6. This acceptance covers one clean synthetic crop and API persistence only. It does not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or event retention/privacy suitability. +5. Human confirmation acceptance passed in source-built disposable project `hmd-plate-link-1793880442-bff1ca`: the synthetic OCR crop returned `AB-123-CD` at confidence 0.912; a vehicle with another plate was rejected with HTTP 422; PostgreSQL showed both links null before confirmation; explicit confirmation returned 200 and both `license_plates.VehicleId` and `camera_events.VehicleId` were populated; anonymous confirmation returned 401. Cleanup verified zero containers, volumes and networks and removed/verified absence of the exact `heimdall:hmd-plate-link-1793880442-bff1ca-central` image tag. Two earlier recipe attempts had harness-only readiness/SQL identifier mistakes; each exact project and tag was cleaned and absence checked. +6. Keep assigning the locally built Central image a unique project tag and remove/verify that exact tag on every recipe completion, including failure paths. Retain shared .NET/ASP.NET base images and never use broad image pruning. +7. These acceptances cover one synthetic crop and the API persistence/confirmation path only. They do not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or event retention/privacy suitability. diff --git a/src/Heimdall.Application/Vehicles/Commands/ConfirmPlateAssociation/ConfirmPlateAssociationCommand.cs b/src/Heimdall.Application/Vehicles/Commands/ConfirmPlateAssociation/ConfirmPlateAssociationCommand.cs new file mode 100644 index 0000000..1fe22fc --- /dev/null +++ b/src/Heimdall.Application/Vehicles/Commands/ConfirmPlateAssociation/ConfirmPlateAssociationCommand.cs @@ -0,0 +1,85 @@ +using System.Text.Json; +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Vehicles.Commands.ConfirmPlateAssociation; + +public sealed record ConfirmPlateAssociationCommand( + Guid CameraId, + Guid PlateId, + Guid EventId, + Guid VehicleId, + Guid UserId) : IRequest>; + +public sealed record PlateAssociationResponse(Guid PlateId, Guid EventId, Guid VehicleId, Guid? PersonId); + +public sealed class ConfirmPlateAssociationCommandHandler( + IApplicationDbContext db, + ICameraAccessService cameraAccess) + : IRequestHandler> +{ + public async Task> Handle( + ConfirmPlateAssociationCommand request, CancellationToken ct) + { + if (request.UserId == Guid.Empty || + !await cameraAccess.HasCameraAccessAsync(request.UserId, request.CameraId, ct).ConfigureAwait(false)) + return ServiceResult.Failure("Camera access denied", 403); + + var plate = await db.LicensePlates + .FirstOrDefaultAsync(p => p.Id == request.PlateId, ct).ConfigureAwait(false); + if (plate is null) + return ServiceResult.NotFound("Plate observation not found"); + + var cameraEvent = await db.CameraEvents + .FirstOrDefaultAsync(e => e.Id == request.EventId && e.CameraId == request.CameraId && + e.Type == EventType.LicensePlateDetected, ct).ConfigureAwait(false); + if (cameraEvent is null || !EventReferencesPlate(cameraEvent.MetadataJson, plate.Id)) + return ServiceResult.NotFound("Plate event not found for this camera"); + + var vehicle = await db.Vehicles + .AsNoTracking() + .FirstOrDefaultAsync(v => v.Id == request.VehicleId, ct).ConfigureAwait(false); + if (vehicle is null) + return ServiceResult.NotFound("Vehicle not found"); + + if (!string.Equals(NormalizePlate(plate.PlateText), NormalizePlate(vehicle.LicensePlate), StringComparison.Ordinal)) + return ServiceResult.Failure("Vehicle plate does not match the observed plate", 422); + + if ((plate.VehicleId.HasValue && plate.VehicleId != vehicle.Id) || + (cameraEvent.VehicleId.HasValue && cameraEvent.VehicleId != vehicle.Id)) + return ServiceResult.Conflict("Plate observation is already linked to another vehicle"); + + if (plate.VehicleId != vehicle.Id || cameraEvent.VehicleId != vehicle.Id) + { + plate.AssignVehicle(vehicle.Id); + cameraEvent.AssignVehicle(vehicle.Id); + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + } + + return ServiceResult.Success( + new(plate.Id, cameraEvent.Id, vehicle.Id, vehicle.PersonId)); + } + + private static bool EventReferencesPlate(string? metadataJson, Guid plateId) + { + if (string.IsNullOrWhiteSpace(metadataJson)) return false; + try + { + using var document = JsonDocument.Parse(metadataJson); + return document.RootElement.TryGetProperty("plateId", out var value) && + value.ValueKind == JsonValueKind.String && value.TryGetGuid(out var actualId) && actualId == plateId; + } + catch (JsonException) + { + return false; + } + } + + private static string NormalizePlate(string? value) => value is null + ? string.Empty + : new string(value.Where(char.IsAsciiLetterOrDigit).Select(char.ToUpperInvariant).ToArray()); +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 7f6b219..2527870 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -58,6 +58,12 @@ public static class DependencyInjection services.AddSingleton(); services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); + services.AddScoped(); + services.AddOptions() + .Bind(configuration.GetSection(RecordingStorageQuotaOptions.SectionName)) + .ValidateDataAnnotations() + .ValidateOnStart(); + services.AddScoped(); // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 0473a1b..dc78268 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -212,6 +212,31 @@ else { @_plateOcrMessage } + @if (_plateOcrResult is not null) + { + @if (_plateVehicleCandidates.Count > 0) + { + @Text["CameraDetail_PlateOcrReview"] + + @foreach (var vehicle in _plateVehicleCandidates) + { + + @FormatPlateVehicle(vehicle) + + } + + + @Text["CameraDetail_PlateOcrConfirm"] + + } + else + { + @Text["CameraDetail_PlateOcrNoVehicle"] + } + } @* ─── Mini-timeline : événements récents ─── *@ @@ -303,6 +328,11 @@ else private bool _recognizingPlate; private bool _plateOcrSuccess; private string? _plateOcrMessage; + private Heimdall.Application.Services.LicensePlateRecognitionResponse? _plateOcrResult; + private List _plateVehicleCandidates = []; + private Guid? _selectedPlateVehicleId; + private bool _confirmingPlate; + private bool _plateAssociationConfirmed; private List? _events; private List _recordings = []; @@ -380,21 +410,84 @@ else _recognizingPlate = true; _plateOcrMessage = null; + _plateOcrResult = null; + _plateVehicleCandidates = []; + _selectedPlateVehicleId = null; + _plateAssociationConfirmed = false; try { await using var stream = file.OpenReadStream(512 * 1024); var response = await Api.RecognizePlateCropAsync(Id, stream, file.ContentType, file.Name); _plateOcrSuccess = response.Succeeded; - _plateOcrMessage = response.Succeeded && response.Data is not null - ? string.Format(Language.Culture, Text["CameraDetail_PlateOcrResult"], response.Data.PlateText, - (response.Data.Confidence * 100).ToString("0", Language.Culture)) - : response.ErrorMessage ?? Text["CameraDetail_OperationFailed"]; - if (response.Succeeded) await LoadEventsAsync(); + if (!response.Succeeded || response.Data is null) + { + _plateOcrMessage = response.ErrorMessage ?? Text["CameraDetail_OperationFailed"]; + return; + } + + _plateOcrResult = response.Data; + _plateOcrMessage = string.Format(Language.Culture, Text["CameraDetail_PlateOcrResult"], response.Data.PlateText, + (response.Data.Confidence * 100).ToString("0", Language.Culture)); + try + { + var candidates = await Api.GetVehiclesAsync(search: response.Data.PlateText, pageSize: 100) ?? []; + _plateVehicleCandidates = candidates + .Where(vehicle => NormalizePlateText(vehicle.LicensePlate) == NormalizePlateText(response.Data.PlateText)) + .ToList(); + if (response.Data.SuggestedVehicleId is Guid suggestedId && + _plateVehicleCandidates.Any(vehicle => vehicle.Id == suggestedId)) + _selectedPlateVehicleId = suggestedId; + } + catch + { + _plateVehicleCandidates = []; + } + await LoadEventsAsync(); } catch { _plateOcrSuccess = false; _plateOcrMessage = Text["CameraDetail_OperationFailed"]; } finally { _recognizingPlate = false; } } + private async Task ConfirmPlateAssociationAsync() + { + if (_plateOcrResult is null || _selectedPlateVehicleId is not Guid vehicleId || _plateAssociationConfirmed || _confirmingPlate) + return; + + _confirmingPlate = true; + try + { + var response = await Api.ConfirmPlateAssociationAsync( + Id, _plateOcrResult.PlateId, _plateOcrResult.EventId, vehicleId); + if (response.Succeeded) + { + _plateAssociationConfirmed = true; + _plateOcrMessage = Text["CameraDetail_PlateOcrLinked"]; + await LoadEventsAsync(); + } + else + { + _plateOcrSuccess = false; + _plateOcrMessage = response.ErrorMessage ?? Text["CameraDetail_OperationFailed"]; + } + } + catch + { + _plateOcrSuccess = false; + _plateOcrMessage = Text["CameraDetail_OperationFailed"]; + } + finally { _confirmingPlate = false; } + } + + private static string NormalizePlateText(string? value) => value is null + ? string.Empty + : new string(value.Where(char.IsAsciiLetterOrDigit).Select(char.ToUpperInvariant).ToArray()); + + private static string FormatPlateVehicle(VehicleClientItem vehicle) + { + var identity = string.Join(" ", new[] { vehicle.Make, vehicle.Model, vehicle.Color }.Where(value => !string.IsNullOrWhiteSpace(value))); + return string.IsNullOrWhiteSpace(identity) ? vehicle.LicensePlate ?? vehicle.Id.ToString("D") : $"{vehicle.LicensePlate} — {identity}"; + } + private async Task LoadRecordingsAsync() { _recordingsLoading = true; diff --git a/src/Heimdall.Web/Controllers/PlateRecognitionController.cs b/src/Heimdall.Web/Controllers/PlateRecognitionController.cs index 2702e81..f719ffd 100644 --- a/src/Heimdall.Web/Controllers/PlateRecognitionController.cs +++ b/src/Heimdall.Web/Controllers/PlateRecognitionController.cs @@ -1,7 +1,9 @@ using Heimdall.Application.Services; +using Heimdall.Application.Vehicles.Commands.ConfirmPlateAssociation; using Heimdall.Api.Security; using Heimdall.Infrastructure.Security; using Heimdall.Infrastructure.Services; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -15,7 +17,8 @@ namespace Heimdall.Api.Controllers; public sealed class PlateRecognitionController( ResourceAccess access, ILicensePlateRecognitionService recognition, - IOptionsMonitor options) : ControllerBase + IOptionsMonitor options, + IMediator mediator) : ControllerBase { private const int MaxCropBytes = 512 * 1024; @@ -45,4 +48,22 @@ public sealed class PlateRecognitionController( var result = await recognition.RecognizeAsync(cameraId, bytes, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 422, new { error = result.Error }); } + + /// Explicitly confirms a human-reviewed plate-to-vehicle association. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.VehicleWrite)] + [HttpPost("{plateId:guid}/confirm")] + public async Task Confirm(Guid cameraId, Guid plateId, ConfirmPlateAssociationRequest request, + CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct); + if (requester is null || requester.Kind != RequesterKind.Human || + !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); + + var result = await mediator.Send(new ConfirmPlateAssociationCommand( + cameraId, plateId, request.EventId, request.VehicleId, requester.Id), ct); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } } + +public sealed record ConfirmPlateAssociationRequest(Guid EventId, Guid VehicleId); diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 557b133..031681b 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -4110,7 +4110,12 @@ Stop live Live view is unavailable. Check the media service and camera access. Local plate reading (manual action) - Select a JPEG/PNG crop of the plate. The image is processed on this Heimdall server and deleted afterward; only the plate observation and history event are stored. Enable the feature in configuration first. + Select a JPEG/PNG crop of the plate. The image is processed on this Heimdall server and deleted afterward; only the plate observation and history event are retained. No vehicle is linked until you explicitly confirm it. Enable the feature in configuration first. Select a JPEG or PNG crop no larger than 512 KiB. - Plate {0} recognized with {1}% confidence; an event was added to history. + Plate {0} recognized with {1}% confidence; the observation remains unlinked until confirmation. + Review the candidate. No vehicle link is created until you confirm it. + Choose a vehicle + Confirm vehicle link + The plate observation and its event are now linked to the selected vehicle. + No matching vehicle was found. The observation remains unlinked. diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 456a691..3d5cad1 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -4110,7 +4110,12 @@ Arrêter le direct Le direct est indisponible. Vérifiez le service média et les droits caméra. Lecture de plaque locale (action manuelle) - Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration. + Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Aucun véhicule n’est lié avant votre confirmation explicite. Activez d’abord la fonction dans la configuration. Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum. - Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique. + Plaque {0} reconnue avec une confiance de {1} %; l’observation reste sans lien jusqu’à confirmation. + Vérifiez la correspondance proposée. Aucun lien véhicule n’est créé avant votre confirmation. + Choisissez le véhicule + Confirmer le lien + L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné. + Aucun véhicule correspondant trouvé. L’observation reste sans lien. diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index 0f31954..e38b556 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -4110,7 +4110,12 @@ Stop live Live view is unavailable. Check the media service and camera access. Lecture de plaque locale (action manuelle) - Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration. + Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Aucun véhicule n’est lié avant votre confirmation explicite. Activez d’abord la fonction dans la configuration. Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum. - Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique. + Plaque {0} reconnue avec une confiance de {1} %; l’observation reste sans lien jusqu’à confirmation. + Vérifiez la correspondance proposée. Aucun lien véhicule n’est créé avant votre confirmation. + Choisissez le véhicule + Confirmer le lien + L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné. + Aucun véhicule correspondant trouvé. L’observation reste sans lien. diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index a8811c9..042b153 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -4,6 +4,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using Heimdall.Application.DTOs; using Heimdall.Application.Services; +using Heimdall.Application.Vehicles.Commands.ConfirmPlateAssociation; namespace Heimdall.Web.Services; @@ -531,6 +532,20 @@ public class HeimdallApiClient : IDisposable : ApiResult.Success(result); } + public async Task> ConfirmPlateAssociationAsync( + Guid cameraId, Guid plateId, Guid eventId, Guid vehicleId, CancellationToken ct = default) + { + using var response = await CreateClient().PostAsJsonAsync( + $"api/cameras/{cameraId:D}/plate-recognition/{plateId:D}/confirm", + new { eventId, vehicleId }, Json, ct); + if (!response.IsSuccessStatusCode) + return ApiResult.Failure(await ReadErrorMessageAsync(response)); + var result = await response.Content.ReadFromJsonAsync(Json, ct); + return result is null + ? ApiResult.Failure(InvalidServerResponse) + : ApiResult.Success(result); + } + public async Task?> GetCameraRecordingsAsync(Guid id, int page = 1, int pageSize = 20) { var client = CreateClient(); @@ -976,10 +991,16 @@ public class HeimdallApiClient : IDisposable // ─── Vehicles (filtered client-side by PersonId) ────────────────── - public async Task?> GetVehiclesAsync(Guid? personId = null) + public async Task?> GetVehiclesAsync( + Guid? personId = null, string? search = null, int page = 1, int pageSize = 50) { var client = CreateClient(); - var query = personId.HasValue ? $"?personId={personId.Value}" : string.Empty; + var parameters = new List(); + if (personId.HasValue) parameters.Add($"personId={personId.Value}"); + if (!string.IsNullOrWhiteSpace(search)) parameters.Add($"search={Uri.EscapeDataString(search)}"); + if (page != 1) parameters.Add($"page={page}"); + if (pageSize != 50) parameters.Add($"pageSize={pageSize}"); + var query = parameters.Count == 0 ? string.Empty : $"?{string.Join('&', parameters)}"; return await client.GetFromJsonAsync>($"api/vehicles{query}", Json); } diff --git a/tests/Heimdall.Application.Tests/Handlers/Vehicles/ConfirmPlateAssociationHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Vehicles/ConfirmPlateAssociationHandlerTests.cs new file mode 100644 index 0000000..98fa490 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Vehicles/ConfirmPlateAssociationHandlerTests.cs @@ -0,0 +1,112 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Services; +using Heimdall.Application.Tests.Common; +using Heimdall.Application.Vehicles.Commands.ConfirmPlateAssociation; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; + +namespace Heimdall.Application.Tests.Handlers.Vehicles; + +public sealed class ConfirmPlateAssociationHandlerTests +{ + [Fact] + public async Task ConfirmsMatchingObservationAndEventOnlyAfterCameraAuthorizedRequest() + { + var userId = Guid.NewGuid(); + var cameraId = Guid.NewGuid(); + var plate = new LicensePlate("AB-123-CD", confidence: 0.91); + var cameraEvent = CreatePlateEvent(cameraId, plate.Id); + var personId = Guid.NewGuid(); + var vehicle = new Vehicle("AB123CD", personId, "Renault", "Clio", "Blue"); + var (handler, db, cameraAccess) = CreateHandler(plate, cameraEvent, vehicle, hasCameraAccess: true); + + var result = await handler.Handle( + new(cameraId, plate.Id, cameraEvent.Id, vehicle.Id, userId), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldBe(new PlateAssociationResponse(plate.Id, cameraEvent.Id, vehicle.Id, personId)); + plate.VehicleId.ShouldBe(vehicle.Id); + cameraEvent.VehicleId.ShouldBe(vehicle.Id); + await cameraAccess.Received(1).HasCameraAccessAsync(userId, cameraId, Arg.Any()); + await db.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task RejectsAssociationWhenCameraAccessIsMissing() + { + var cameraId = Guid.NewGuid(); + var plate = new LicensePlate("AB-123-CD"); + var cameraEvent = CreatePlateEvent(cameraId, plate.Id); + var vehicle = new Vehicle("AB-123-CD"); + var (handler, db, _) = CreateHandler(plate, cameraEvent, vehicle, hasCameraAccess: false); + + var result = await handler.Handle( + new(cameraId, plate.Id, cameraEvent.Id, vehicle.Id, Guid.NewGuid()), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(403); + plate.VehicleId.ShouldBeNull(); + cameraEvent.VehicleId.ShouldBeNull(); + await db.DidNotReceive().SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task RejectsEventFromAnotherCameraOrForAnotherPlate() + { + var cameraId = Guid.NewGuid(); + var plate = new LicensePlate("AB-123-CD"); + var otherPlate = new LicensePlate("XY-999-ZZ"); + var cameraEvent = CreatePlateEvent(cameraId, otherPlate.Id); + var vehicle = new Vehicle("AB-123-CD"); + var (handler, db, _) = CreateHandler(plate, cameraEvent, vehicle, hasCameraAccess: true); + + var result = await handler.Handle( + new(cameraId, plate.Id, cameraEvent.Id, vehicle.Id, Guid.NewGuid()), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + plate.VehicleId.ShouldBeNull(); + await db.DidNotReceive().SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task RejectsVehicleWithDifferentPlateText() + { + var cameraId = Guid.NewGuid(); + var plate = new LicensePlate("AB-123-CD"); + var cameraEvent = CreatePlateEvent(cameraId, plate.Id); + var vehicle = new Vehicle("XY-999-ZZ"); + var (handler, db, _) = CreateHandler(plate, cameraEvent, vehicle, hasCameraAccess: true); + + var result = await handler.Handle( + new(cameraId, plate.Id, cameraEvent.Id, vehicle.Id, Guid.NewGuid()), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(422); + plate.VehicleId.ShouldBeNull(); + cameraEvent.VehicleId.ShouldBeNull(); + await db.DidNotReceive().SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + + private static (ConfirmPlateAssociationCommandHandler Handler, IApplicationDbContext Db, ICameraAccessService CameraAccess) + CreateHandler(LicensePlate plate, CameraEvent cameraEvent, Vehicle vehicle, bool hasCameraAccess) + { + var db = Substitute.For(); + db.LicensePlates.Returns(MockDbSetHelper.CreateFor([plate])); + db.CameraEvents.Returns(MockDbSetHelper.CreateFor([cameraEvent])); + db.Vehicles.Returns(MockDbSetHelper.CreateFor([vehicle])); + db.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var cameraAccess = Substitute.For(); + cameraAccess.HasCameraAccessAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(hasCameraAccess); + return (new ConfirmPlateAssociationCommandHandler(db, cameraAccess), db, cameraAccess); + } + + private static CameraEvent CreatePlateEvent(Guid cameraId, Guid plateId) + { + var cameraEvent = new CameraEvent(cameraId, EventType.LicensePlateDetected, 0.91); + cameraEvent.SetMetadata("AB-123-CD", $$"""{"source":"local-opt-in-ocr","plateId":"{{plateId}}"}"""); + return cameraEvent; + } +} diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs index 69abeb4..f80b6d3 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -1,5 +1,6 @@ using Bunit; using Bunit.TestDoubles; +using Heimdall.Application.Vehicles.Commands.ConfirmPlateAssociation; using Heimdall.Web.Components.Pages; using Heimdall.Web.Services; using Microsoft.Extensions.DependencyInjection; @@ -27,6 +28,26 @@ public class CameraDetailTests : PageTestBase private void HandlerCamera(CameraItem camera) => Handler.OnGet("api/cameras/", camera); + [Fact] + public async Task PlateAssociationConfirmation_PostsCameraPlateEventAndVehicleIds() + { + var plateId = Guid.NewGuid(); + var eventId = Guid.NewGuid(); + var vehicleId = Guid.NewGuid(); + var expected = new PlateAssociationResponse(plateId, eventId, vehicleId, null); + Handler.On(HttpMethod.Post, $"plate-recognition/{plateId:D}/confirm", expected); + + var result = await Api.ConfirmPlateAssociationAsync(CameraId, plateId, eventId, vehicleId); + + result.Succeeded.ShouldBeTrue(); + result.Data.ShouldBe(expected); + var request = Handler.Requests.Single(); + request.RequestUri!.AbsolutePath.ShouldBe($"/api/cameras/{CameraId:D}/plate-recognition/{plateId:D}/confirm"); + using var body = System.Text.Json.JsonDocument.Parse(await request.Content!.ReadAsStringAsync()); + body.RootElement.GetProperty("eventId").GetGuid().ShouldBe(eventId); + body.RootElement.GetProperty("vehicleId").GetGuid().ShouldBe(vehicleId); + } + [Fact] public void CameraDetail_AfficheInformationsEtStatut() { diff --git a/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs b/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs index 6649725..9c915f1 100644 --- a/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs +++ b/tests/Heimdall.Web.Tests/Controllers/PlateRecognitionControllerTests.cs @@ -3,6 +3,7 @@ using Heimdall.Application.Services; using Heimdall.Infrastructure.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; +using MediatR; using NSubstitute; using Xunit; @@ -16,7 +17,7 @@ public sealed class PlateRecognitionControllerTests var config = Substitute.For>(); config.CurrentValue.Returns(new PlateOcrOptions()); var service = Substitute.For(); - var controller = new PlateRecognitionController(null!, service, config); + var controller = new PlateRecognitionController(null!, service, config, Substitute.For()); var result = await controller.Recognize(Guid.NewGuid(), null, CancellationToken.None); diff --git a/todo.md b/todo.md index eaa0c5b..5c32a58 100644 --- a/todo.md +++ b/todo.md @@ -47,7 +47,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès (2/2 tests Agent ciblés). La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. -- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, API opt-in par défaut 1/1. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent; cleanup 0 conteneur/0 volume/0 réseau. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); workflow de confirmation et liaison d’identité; rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. +- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` repassé le 5 novembre après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. -- 2.54.1 From 7d1a4b627740c0a786513e04dc9ebfd391685099 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 13:29:03 +0100 Subject: [PATCH 23/40] feat: support person and vehicle analysis jobs --- skills/analysis-job-pipeline/SKILL.md | 30 ++++++++++ .../Services/AnalysisJobPollingService.cs | 38 ++++++++++--- .../Services/AnalysisJobSchedulerService.cs | 5 +- .../Controllers/AnalysisJobsController.cs | 5 +- .../AnalysisJobPollingServiceTests.cs | 56 ++++++++++++++++++ .../AnalysisJobSchedulerServiceTests.cs | 33 +++++++++++ .../Scenarios/AnalysisJobScenarios.cs | 57 +++++++++++++++++++ todo.md | 2 +- 8 files changed, 214 insertions(+), 12 deletions(-) create mode 100644 skills/analysis-job-pipeline/SKILL.md create mode 100644 tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs diff --git a/skills/analysis-job-pipeline/SKILL.md b/skills/analysis-job-pipeline/SKILL.md new file mode 100644 index 0000000..dbe270e --- /dev/null +++ b/skills/analysis-job-pipeline/SKILL.md @@ -0,0 +1,30 @@ +--- +name: analysis-job-pipeline +description: Implement and verify analysis job types across Heimdall Central scheduling and Agent inference. +--- + +# Heimdall analysis job pipeline + +Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet/SKILL.md`. For database behavior, also follow `skills/ef-core-persistence/SKILL.md`. + +## Current supported job types + +- `ObjectDetection`: return every detection produced by the configured YOLO COCO model. +- `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`). +- `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`). Keep the model label, confidence, box and class index in the result. +- The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result. +- Motion detection needs temporal frame comparison; face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection. +- Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types. + +## Required validation + +1. Unit-test Agent type parsing and the exact COCO class filtering for all three supported types, including empty results and unsupported types. +2. Run PostgreSQL scheduler tests proving CPU/RAM requirements for supported types and refusal of unsupported types. Do not substitute EF InMemory for relational behavior. +3. Run the PostgreSQL integration scenario through the Web API: create each supported job, dispatch to the assigned online Agent, claim it with the Agent API key, submit a result, and verify persisted completion. Verify unsupported type requests receive HTTP 400. +4. Build Central from the changed source in a uniquely tagged disposable Compose project with generated credentials, loopback-only ports, project-owned volumes/network, empty Sentry DSN, and OCR disabled unless the scenario explicitly needs it. Bootstrap synthetic Admin/site/camera, register and heartbeat a synthetic Agent, assign the camera, submit supported and unsupported job types, and verify the lease/result boundary where practical. +5. Tear down that exact Compose project, verify zero project containers/volumes/networks, remove every source-built image tag from this recipe and verify each exact tag is absent. Retain shared Postgres/.NET base images. Never use broad prune commands. +6. Keep hardware, camera-stream inference, and real multi-Agent deployment claims separate from synthetic database/API acceptance. + +## Current local acceptance evidence + +On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections; it does not prove inference from camera frames, MotionDetection, face/plate models, anomaly detection, full-scene analysis, or deployed multi-Agent behavior. diff --git a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs index 127a0c1..1bee4a1 100644 --- a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs +++ b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs @@ -82,7 +82,7 @@ public sealed class AnalysisJobPollingService : BackgroundService private async Task ExecuteJobAsync(LeasedJob job, CancellationToken ct) { - if (!IsObjectDetection(job.JobType)) + if (!TryGetSupportedJobType(job.JobType, out var jobType)) return Failure(job.AttemptId, "Unsupported analysis job type"); var camera = _cameras.Cameras.FirstOrDefault(c => c.CameraId == job.CameraId && c.Enabled); @@ -110,7 +110,8 @@ public sealed class AnalysisJobPollingService : BackgroundService if (analysis is null) return Failure(job.AttemptId, "Object detection was unavailable or saturated"); - return new AnalysisResult(job.AttemptId, true, null, analysis.Detections + var detections = SelectDetections(jobType, analysis.Detections); + return new AnalysisResult(job.AttemptId, true, null, detections .Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex)) .ToArray()); } @@ -154,14 +155,37 @@ public sealed class AnalysisJobPollingService : BackgroundService } } - private static bool IsObjectDetection(JsonElement type) => type.ValueKind switch + internal static IReadOnlyList SelectDetections( + AnalysisJobType jobType, IReadOnlyList detections) => jobType switch { - JsonValueKind.String => string.Equals(type.GetString(), nameof(AnalysisJobType.ObjectDetection), - StringComparison.OrdinalIgnoreCase), - JsonValueKind.Number => type.TryGetInt32(out var value) && value == (int)AnalysisJobType.ObjectDetection, - _ => false, + AnalysisJobType.ObjectDetection => detections, + AnalysisJobType.PersonDetection => detections.Where(IsPerson).ToArray(), + AnalysisJobType.VehicleClassification => detections.Where(IsVehicle).ToArray(), + _ => [], }; + private static bool IsPerson(DetectionResult detection) => + detection.ClassIndex == 0 || string.Equals(detection.Label, "person", StringComparison.OrdinalIgnoreCase); + + private static bool IsVehicle(DetectionResult detection) => + detection.ClassIndex is 2 or 3 or 5 or 7 || detection.Label.ToLowerInvariant() is "car" or "motorcycle" or "bus" or "truck"; + + internal static bool TryGetSupportedJobType(JsonElement type, out AnalysisJobType jobType) + { + if (type.ValueKind == JsonValueKind.String && Enum.TryParse(type.GetString(), true, out jobType)) + return IsSupported(jobType); + if (type.ValueKind == JsonValueKind.Number && type.TryGetInt32(out var value) && Enum.IsDefined(typeof(AnalysisJobType), value)) + { + jobType = (AnalysisJobType)value; + return IsSupported(jobType); + } + jobType = default; + return false; + } + + private static bool IsSupported(AnalysisJobType type) => type is AnalysisJobType.ObjectDetection or + AnalysisJobType.PersonDetection or AnalysisJobType.VehicleClassification; + private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []); private static bool TryGetMinConfidence(string? parametersJson, out float confidence) diff --git a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs index 810b9ee..7a39417 100644 --- a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs +++ b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs @@ -45,8 +45,9 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService if (camera is null) return ServiceResult.NotFound("Camera not found"); - if (jobType != AnalysisJobType.ObjectDetection) - return ServiceResult.Failure("Only ObjectDetection jobs are currently supported"); + if (jobType is not (AnalysisJobType.ObjectDetection or AnalysisJobType.PersonDetection or + AnalysisJobType.VehicleClassification)) + return ServiceResult.Failure($"Analysis jobs of type {jobType} are not currently supported"); var job = new AnalysisJob(cameraId, camera.SiteId, jobType, priority, parametersJson); diff --git a/src/Heimdall.Web/Controllers/AnalysisJobsController.cs b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs index e1ffb2e..66d63b1 100644 --- a/src/Heimdall.Web/Controllers/AnalysisJobsController.cs +++ b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs @@ -36,8 +36,9 @@ public sealed class AnalysisJobsController( if (requester is null || requester.Kind != RequesterKind.Human || !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); if (!Enum.TryParse(request.JobType, true, out var type) || - type != AnalysisJobType.ObjectDetection) - return BadRequest(new { error = "Only ObjectDetection jobs are currently supported" }); + type is not (AnalysisJobType.ObjectDetection or AnalysisJobType.PersonDetection or + AnalysisJobType.VehicleClassification)) + return BadRequest(new { error = "Supported analysis job types are ObjectDetection, PersonDetection, and VehicleClassification" }); if (request.ParametersJson is { Length: > 16_384 } || !IsValidParameters(request.ParametersJson)) return BadRequest(new { error = "ParametersJson may contain only minConfidence, a number from 0 to 1, and must be at most 16 KiB" }); diff --git a/tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs b/tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs new file mode 100644 index 0000000..7dbc611 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs @@ -0,0 +1,56 @@ +using System.Text.Json; +using Heimdall.Agent.Services; +using Heimdall.Domain.Enums; + +namespace Heimdall.Agent.Tests; + +public sealed class AnalysisJobPollingServiceTests +{ + private static readonly DetectionResult[] CocoDetections = + [ + new("person", 0.91f, 0.1f, 0.2f, 0.2f, 0.5f, 0), + new("bicycle", 0.82f, 0.2f, 0.2f, 0.3f, 0.4f, 1), + new("car", 0.88f, 0.4f, 0.3f, 0.4f, 0.3f, 2), + new("bus", 0.77f, 0.5f, 0.2f, 0.3f, 0.4f, 5), + ]; + + [Fact] + public void SelectDetections_PersonDetection_ReturnsOnlyPersonClass() + { + var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.PersonDetection, CocoDetections); + + result.Select(d => d.Label).ShouldBe(["person"]); + } + + [Fact] + public void SelectDetections_VehicleClassification_ReturnsCocoMotorVehicles() + { + var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.VehicleClassification, CocoDetections); + + result.Select(d => d.Label).ShouldBe(["car", "bus"]); + } + + [Fact] + public void SelectDetections_ObjectDetection_PreservesAllModelClasses() + { + var result = AnalysisJobPollingService.SelectDetections(AnalysisJobType.ObjectDetection, CocoDetections); + + result.ShouldBe(CocoDetections); + } + + [Theory] + [InlineData("\"PersonDetection\"", true)] + [InlineData("\"vehicLeClassification\"", true)] + [InlineData("3", true)] + [InlineData("5", true)] + [InlineData("0", false)] + [InlineData("\"FaceRecognition\"", false)] + [InlineData("\"not-a-job\"", false)] + public void SupportedJobTypes_AcceptsOnlyImplementedContracts(string json, bool expected) + { + using var document = JsonDocument.Parse(json); + var actual = AnalysisJobPollingService.TryGetSupportedJobType(document.RootElement, out _); + + actual.ShouldBe(expected); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs index 4d04bb2..d0bd8fd 100644 --- a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs @@ -128,6 +128,39 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime result.Data.RequiredMemoryMb.ShouldBe(2048); } + [Theory] + [InlineData(AnalysisJobType.PersonDetection, 1024)] + [InlineData(AnalysisJobType.VehicleClassification, 1024)] + public async Task CreateJobAsync_SupportedFilteredDetectionTypes_SetsCpuRequirements( + AnalysisJobType type, int memoryMb) + { + var (_, cameraId) = await SeedSiteAndCameraAsync(); + + var result = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.JobType.ShouldBe(type); + result.Data.RequiresGpu.ShouldBeFalse(); + result.Data.RequiredCpuCores.ShouldBe(2); + result.Data.RequiredMemoryMb.ShouldBe(memoryMb); + } + + [Theory] + [InlineData(AnalysisJobType.MotionDetection)] + [InlineData(AnalysisJobType.FaceRecognition)] + [InlineData(AnalysisJobType.LicensePlateDetection)] + [InlineData(AnalysisJobType.AnomalyDetection)] + [InlineData(AnalysisJobType.FullSceneAnalysis)] + public async Task CreateJobAsync_UnimplementedDetectionTypes_ReturnsFailure(AnalysisJobType type) + { + var (_, cameraId) = await SeedSiteAndCameraAsync(); + + var result = await _service.CreateJobAsync(cameraId, type, AnalysisJobPriority.Periodic); + + result.IsSuccess.ShouldBeFalse(); + result.Error!.ShouldContain(type.ToString()); + } + // ── SelectBestAgent ───────────────────────────────────────────── [Fact] diff --git a/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs b/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs index ee660d2..931c2e9 100644 --- a/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs +++ b/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs @@ -14,6 +14,63 @@ namespace Heimdall.IntegrationTests.Scenarios; [Collection("Postgres")] public sealed class AnalysisJobScenarios(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres) { + [Theory] + [InlineData("PersonDetection")] + [InlineData("VehicleClassification")] + public async Task AnalysisJob_SupportedFilteredDetectionType_IsScheduledAndClaimed(string jobType) + { + var admin = await Factory.CreateAdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", new + { + name = $"Analysis {Guid.NewGuid():N}", + timezone = "UTC" + }); + siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var siteId = (await siteResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + var agent = await RegisterAgentAsync(admin, siteId, $"analysis-{jobType}"); + var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name = $"{jobType} camera", + rtspUrl = "rtsp://127.0.0.1/test" + }); + cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var cameraId = (await cameraResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + (await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId = agent.Id })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + + var unsupported = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", + new { jobType = "MotionDetection" }); + unsupported.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + + var created = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", new { jobType }); + created.StatusCode.ShouldBe(HttpStatusCode.Accepted); + var jobId = (await created.Content.ReadFromJsonAsync()).GetProperty("jobId").GetGuid(); + await DispatchPendingJobsAsync(); + + var claim = await ClaimNextAsync(agent); + claim.StatusCode.ShouldBe(HttpStatusCode.OK); + var lease = await claim.Content.ReadFromJsonAsync(); + lease.GetProperty("jobType").GetString().ShouldBe(jobType); + + var completed = await AgentClient(agent.ApiKey).PutAsJsonAsync( + $"api/agents/{agent.Id}/analysis-jobs/{jobId}/result", + new + { + attemptId = lease.GetProperty("attemptId").GetGuid(), + success = true, + detections = new[] { new { label = jobType == "PersonDetection" ? "person" : "car", + confidence = 0.93, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } } + }); + completed.StatusCode.ShouldBe(HttpStatusCode.NoContent); + var persisted = await admin.GetAsync($"api/cameras/{cameraId}/analysis-jobs/{jobId}"); + persisted.StatusCode.ShouldBe(HttpStatusCode.OK); + var persistedJob = await persisted.Content.ReadFromJsonAsync(); + persistedJob.GetProperty("status").ToString().ShouldBe("Completed"); + persistedJob.GetProperty("resultJson").GetString()!.ShouldContain( + jobType == "PersonDetection" ? "person" : "car"); + } + [Fact] public async Task AnalysisJob_RetriesOnReassignedAgent_AndRejectsLatePreviousAttempt() { diff --git a/todo.md b/todo.md index 5c32a58..fb7a6d0 100644 --- a/todo.md +++ b/todo.md @@ -25,7 +25,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **EF Core / règles de persistance** La PR #116 remplace l’ADO.NET des deux outboxes Agent et du catalogue caméra par EF Core SQLite, préserve les bases locales existantes avec une adoption de schéma testée, et bloque en CI les commandes directes non autorisées. Elle ajoute la skill `skills/ef-core-persistence/`, relie les règles du dépôt au skill et documente les exceptions PostgreSQL spécifiques. Son run PR #390 a passé les tests/builds, les scans serveur/Agent et `CI policy`; fusionnée sur `main` (`9e0eeb8`). - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. -- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. +- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection` et `VehicleClassification` sont maintenant acceptés par l’API et le scheduler et utilisent le même modèle YOLO COCO, filtré respectivement sur personne (classe 0) et véhicules motorisés (classes 2/3/5/7); les autres types restent refusés tant que leurs algorithmes/modèles ne sont pas implémentés. Tests ciblés Agent 10/10, scheduler PostgreSQL 10/10, scénario d’intégration des deux types 2/2. Compose source jetable `hmd-analysis-1793881315-5ba569` : Agent synthétique enregistré/heartbeaté et caméra assignée; MotionDetection rejeté HTTP 400; jobs personne/véhicule créés, dispatchés, réclamés, complétés et résultats relus via API après persistance PostgreSQL. Tag source dédié supprimé/vérifié absent, teardown zéro conteneur/volume/réseau. Reste : inférence réelle sur flux de caméra synthétique, MotionDetection temporel, reconnaissance faciale/plaque et autres modèles/types, ainsi que validation sur deux Agents déployés. Skill : `skills/analysis-job-pipeline/SKILL.md`. - [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé. -- 2.54.1 From f236298fc453d796c1de0ed9149b11aa2235170e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 13:40:34 +0100 Subject: [PATCH 24/40] test: verify stale agent failover across peers --- skills/heartbeat-failover/SKILL.md | 27 +++++ .../Scenarios/AgentFailoverScenarios.cs | 104 ++++++++++++++++++ todo.md | 2 +- 3 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 skills/heartbeat-failover/SKILL.md create mode 100644 tests/Heimdall.IntegrationTests/Scenarios/AgentFailoverScenarios.cs diff --git a/skills/heartbeat-failover/SKILL.md b/skills/heartbeat-failover/SKILL.md new file mode 100644 index 0000000..8693d59 --- /dev/null +++ b/skills/heartbeat-failover/SKILL.md @@ -0,0 +1,27 @@ +--- +name: heartbeat-failover +description: Validate that stale Agents are marked offline and assigned cameras move safely to online peers. +--- + +# Heimdall heartbeat and Agent failover + +Read `AGENTS.md`, the Heartbeat/failover item in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this path. + +## Behavior contract + +- Use the configured global heartbeat interval or per-Agent override, bounded to 5–300 seconds. A stale Agent is not eligible for new work. +- The failover sweep owns the stale-to-Offline transition and camera reassignment. Do not add a competing heartbeat monitor that races this transition. +- Preserve camera assignment history: close the old row and create a new active row for an online Agent in the same site. If there is no replacement, clear the active assignment and let periodic reconciliation retry when an Agent recovers. +- Use short-lived EF Core contexts and test status, camera ownership, and assignment history against PostgreSQL. + +## Required validation + +1. Run the PostgreSQL tests in `HeartbeatMonitorJobTests`, `AgentFailoverJobTests`, and `CameraAssignmentServiceTests`. +2. Run the integration scenario with two registered Agents: heartbeat both, assign a camera to the source, age only the source heartbeat past the maximum accepted timeout, execute the real `AgentFailoverJob` and `CameraAssignmentService`, then verify the source is Offline, the online peer owns the camera, and both assignment records retain the correct released/active state. +3. Build Central from the changed source in a unique disposable Compose project. Generate database/JWT credentials, use unique loopback ports, network, volumes and image tag, empty Sentry DSN, bootstrap a synthetic admin/site and two synthetic Agents, and assign a synthetic camera. Age the source heartbeat only in the disposable PostgreSQL fixture and let the real Hangfire recurring failover job run; verify the active assignment and historical rows through API/PostgreSQL. +4. Tear down that project with volumes/orphans, verify zero project containers, volumes and networks, then remove and verify absence of the exact source-built Central image tag. Keep upstream Postgres/.NET base images; never run broad image pruning. +5. Mark physical Agent loss, network partitions and multi-host timing as unverified unless exercised against deployed Agents. + +## Current local evidence + +5 November 2026: new relational integration scenario passed 1/1. Disposable source-built project `hmd-failover-1793882220-a9bc9c` registered two Agents, assigned the synthetic camera to the first, aged its heartbeat to 900 seconds, and observed the real Hangfire failover mark it Offline and move the camera to the still-online peer. PostgreSQL confirmed the previous assignment was released and the replacement assignment active. Teardown left zero containers/volumes/networks and removed/verified absence of the exact Central image tag. This proves the local scheduled path and relational state, not a real network partition or deployed multi-host timing. diff --git a/tests/Heimdall.IntegrationTests/Scenarios/AgentFailoverScenarios.cs b/tests/Heimdall.IntegrationTests/Scenarios/AgentFailoverScenarios.cs new file mode 100644 index 0000000..154e25e --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Scenarios/AgentFailoverScenarios.cs @@ -0,0 +1,104 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Application.Services; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Jobs; +using Heimdall.IntegrationTests.Controllers; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace Heimdall.IntegrationTests.Scenarios; + +[Collection("Postgres")] +public sealed class AgentFailoverScenarios(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres) +{ + [Fact] + public async Task StaleAgent_IsMarkedOfflineAndCameraMovesToOnlinePeer() + { + var admin = await Factory.CreateAdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", new + { + name = $"Failover {Guid.NewGuid():N}", + timezone = "UTC" + }); + siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var siteId = (await siteResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + var failedAgent = await RegisterAgentAsync(admin, siteId, "failover-source"); + var replacementAgent = await RegisterAgentAsync(admin, siteId, "failover-replacement"); + var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name = "Failover camera", + rtspUrl = "rtsp://127.0.0.1/synthetic" + }); + cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var cameraId = (await cameraResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + (await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId = failedAgent.Id })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + + await using (var scope = Factory.Services.CreateAsyncScope()) + { + var dbFactory = scope.ServiceProvider.GetRequiredService>(); + await using var db = await dbFactory.CreateDbContextAsync(); + await db.Agents.Where(agent => agent.Id == failedAgent.Id) + .ExecuteUpdateAsync(setters => setters.SetProperty(agent => agent.LastHeartbeat, + DateTime.UtcNow.AddSeconds(-900))); + } + + await using (var scope = Factory.Services.CreateAsyncScope()) + { + var services = scope.ServiceProvider; + var job = new AgentFailoverJob( + services.GetRequiredService>(), + services.GetRequiredService(), + services.GetRequiredService>()); + await job.ExecuteAsync(); + } + + await using (var scope = Factory.Services.CreateAsyncScope()) + { + var dbFactory = scope.ServiceProvider.GetRequiredService>(); + await using var db = await dbFactory.CreateDbContextAsync(); + (await db.Agents.Where(agent => agent.Id == failedAgent.Id).Select(agent => agent.Status).SingleAsync()) + .ShouldBe(AgentStatus.Offline); + (await db.Cameras.Where(camera => camera.Id == cameraId).Select(camera => camera.AgentId).SingleAsync()) + .ShouldBe(replacementAgent.Id); + var assignments = await db.CameraAssignments.Where(assignment => assignment.CameraId == cameraId) + .OrderBy(assignment => assignment.AssignedAt).ToListAsync(); + assignments.Count.ShouldBe(2); + assignments[0].ReleasedAt.ShouldNotBeNull(); + assignments[0].AgentId.ShouldBe(failedAgent.Id); + assignments[1].ReleasedAt.ShouldBeNull(); + assignments[1].AgentId.ShouldBe(replacementAgent.Id); + } + } + + private async Task<(Guid Id, string ApiKey)> RegisterAgentAsync(HttpClient admin, Guid siteId, string hostname) + { + var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var siteToken = (await tokenResponse.Content.ReadFromJsonAsync()).GetProperty("token").GetString()!; + var registration = await admin.PostAsJsonAsync("api/agents/register", new + { + token = siteToken, + hostname, + version = "1.0.0-test" + }); + registration.StatusCode.ShouldBe(HttpStatusCode.OK); + var registered = await registration.Content.ReadFromJsonAsync(); + var id = registered.GetProperty("agentId").GetGuid(); + var apiKey = registered.GetProperty("apiKey").GetString()!; + var heartbeat = Factory.CreateClient(); + heartbeat.DefaultRequestHeaders.Add("X-API-Key", apiKey); + (await heartbeat.PostAsJsonAsync($"api/agents/{id}/heartbeat", new + { + publicIp = "127.0.0.1", + cpuCores = 4, + memoryMb = 4096 + })).StatusCode.ShouldBe(HttpStatusCode.OK); + return (id, apiKey); + } +} diff --git a/todo.md b/todo.md index fb7a6d0..28adde5 100644 --- a/todo.md +++ b/todo.md @@ -26,7 +26,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection` et `VehicleClassification` sont maintenant acceptés par l’API et le scheduler et utilisent le même modèle YOLO COCO, filtré respectivement sur personne (classe 0) et véhicules motorisés (classes 2/3/5/7); les autres types restent refusés tant que leurs algorithmes/modèles ne sont pas implémentés. Tests ciblés Agent 10/10, scheduler PostgreSQL 10/10, scénario d’intégration des deux types 2/2. Compose source jetable `hmd-analysis-1793881315-5ba569` : Agent synthétique enregistré/heartbeaté et caméra assignée; MotionDetection rejeté HTTP 400; jobs personne/véhicule créés, dispatchés, réclamés, complétés et résultats relus via API après persistance PostgreSQL. Tag source dédié supprimé/vérifié absent, teardown zéro conteneur/volume/réseau. Reste : inférence réelle sur flux de caméra synthétique, MotionDetection temporel, reconnaissance faciale/plaque et autres modèles/types, ainsi que validation sur deux Agents déployés. Skill : `skills/analysis-job-pipeline/SKILL.md`. -- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire. +- [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures utilisent un heartbeat vieux de 900 s. Le run PR #276 a validé build/tests et scans des images serveur et Agent. Nouvelle preuve relationnelle locale le 5 novembre 2026 : scénario PostgreSQL deux Agents 1/1; le job réel marque Offline l’Agent périmé, réaffecte la caméra au pair en ligne et conserve les deux lignes d’historique (ancienne libérée, nouvelle active). Compose source `hmd-failover-1793882220-a9bc9c` a laissé tourner le failover Hangfire réel après vieillissement contrôlé du heartbeat; API + PostgreSQL ont confirmé le changement et l’état Offline. Cleanup zéro conteneur/volume/réseau et tag image source dédié supprimé/vérifié absent. La perte d’un Agent déployé, les partitions réseau et la synchronisation multi-hôte restent à mesurer en réel. Skill : `skills/heartbeat-failover/SKILL.md`. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé. - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. -- 2.54.1 From c61d7183bf194e030024b361f8f58c36aeb71cd0 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 13:55:26 +0100 Subject: [PATCH 25/40] fix: normalize settings keys for notification delivery --- .../notification-delivery-acceptance/SKILL.md | 27 ++++++++++++ .../Settings/AppSettingReader.cs | 5 ++- .../Settings/AppSettingReaderTests.cs | 42 +++++++++++++++++++ todo.md | 2 +- 4 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 skills/notification-delivery-acceptance/SKILL.md create mode 100644 tests/Heimdall.Infrastructure.Tests/Settings/AppSettingReaderTests.cs diff --git a/skills/notification-delivery-acceptance/SKILL.md b/skills/notification-delivery-acceptance/SKILL.md new file mode 100644 index 0000000..d1ce87c --- /dev/null +++ b/skills/notification-delivery-acceptance/SKILL.md @@ -0,0 +1,27 @@ +--- +name: notification-delivery-acceptance +description: Validate Heimdall's global SMTP and ntfy settings, test actions, and notification delivery without external providers. +--- + +# Heimdall notification delivery acceptance + +Read `AGENTS.md`, PIPE-10/FEAT-05 in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing notification delivery. + +## Configuration contract + +- Settings created through the UI are stored with lowercase keys. `AppSettingReader` must normalize requested keys before its exact EF query; callers use mixed-case literals for legacy reasons. +- SMTP reads `email.smtphost`, `email.smtpport`, `email.username`, `email.password`, `email.fromaddress`, `email.fromname`, and `email.usessl`. +- ntfy reads `ntfy.baseurl` and `ntfy.token`; test messages use the same configured service and should fail visibly when it rejects or cannot be reached. +- Keep SMTP/ntfy secrets out of responses and logs. Outbox delivery remains at-least-once; a provider acceptance followed by a lost DB acknowledgement can duplicate a notification. + +## Required simulated validation + +1. Run `AppSettingReaderTests`, notification service/outbox tests, and the PostgreSQL outbox integration tests. +2. Use a disposable Compose project from the changed Central source with PostgreSQL, an isolated ntfy service and Mailpit. Generate database/JWT credentials, use an internal project-only network and no published ports, explicitly empty the Sentry DSN, and keep real SMTP/ntfy credentials out of the environment. +3. Bootstrap a synthetic Admin and save SMTP/ntfy settings through `/api/settings`, matching UI key names. Call `/api/settings/ntfy/test` and `/api/settings/email/test`; verify ntfy returns success and Mailpit stores the synthetic recipient message. +4. Tear down only the project with volumes/orphans, verify zero project containers/volumes/networks, and remove/verify absence of the exact source-built Central image tag. Retain shared ntfy/Mailpit/PostgreSQL/Python base images and never use broad prune commands. +5. Report local service acceptance separately from delivery to a real SMTP relay, hosted ntfy server, or user device. + +## Current local evidence + +On 5 November 2026, `AppSettingReaderTests` passed 9/9. The first disposable provider run showed ntfy success but SMTP failure: the UI stored lowercase keys while `EmailService` queried mixed-case values. `AppSettingReader.GetAsync` now lowercases trimmed keys; tests cover the SMTP and AI URL callers. The source-built isolated project `hmd-notify-mock-1793882996-2efa06` then passed both Admin settings/API test routes, ntfy HTTP 2xx, and SMTP test delivery captured in Mailpit. No ports were published and the bridge was internal. Cleanup verified zero containers/volumes/networks and removed/verified absence of the exact Central image tag. Real external delivery remains unvalidated. diff --git a/src/Heimdall.Infrastructure/Settings/AppSettingReader.cs b/src/Heimdall.Infrastructure/Settings/AppSettingReader.cs index d6c1375..cf4788d 100644 --- a/src/Heimdall.Infrastructure/Settings/AppSettingReader.cs +++ b/src/Heimdall.Infrastructure/Settings/AppSettingReader.cs @@ -13,11 +13,14 @@ public static class AppSettingReader { public static async Task GetAsync(IApplicationDbContext db, string key, CancellationToken ct = default) { + if (string.IsNullOrWhiteSpace(key)) return null; + + var normalizedKey = key.Trim().ToLowerInvariant(); try { return await db.AppSettings .AsNoTracking() - .Where(s => s.Key == key) + .Where(s => s.Key == normalizedKey) .Select(s => s.Value) .FirstOrDefaultAsync(ct) .ConfigureAwait(false); diff --git a/tests/Heimdall.Infrastructure.Tests/Settings/AppSettingReaderTests.cs b/tests/Heimdall.Infrastructure.Tests/Settings/AppSettingReaderTests.cs new file mode 100644 index 0000000..21102c6 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/Settings/AppSettingReaderTests.cs @@ -0,0 +1,42 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Infrastructure.Settings; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests.Settings; + +public sealed class AppSettingReaderTests +{ + [Theory] + [InlineData("email.smtpHost", "email.smtphost", "mailpit")] + [InlineData("email.smtpPort", "email.smtpport", "1025")] + [InlineData("email.fromAddress", "email.fromaddress", "synthetic@example.invalid")] + [InlineData("email.useSsl", "email.usessl", "false")] + [InlineData("ai.cpaiUrl", "ai.cpaiurl", "http://codeproject-ai")] + [InlineData("ai.ollamaUrl", "ai.ollamaurl", "http://ollama")] + public async Task GetAsync_NormalizesKeyLikeSettingsUi(string requestedKey, string storedKey, string value) + { + var db = Substitute.For(); + db.AppSettings.Returns(MockDbSetHelper.CreateFor([new AppSetting(storedKey, value)])); + + var result = await AppSettingReader.GetAsync(db, requestedKey); + + result.ShouldBe(value); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetAsync_EmptyKey_ReturnsNullWithoutQuery(string? key) + { + var db = Substitute.For(); + db.AppSettings.Returns(MockDbSetHelper.CreateFor([])); + + var result = await AppSettingReader.GetAsync(db, key!); + + result.ShouldBeNull(); + } +} diff --git a/todo.md b/todo.md index 28adde5..71947c1 100644 --- a/todo.md +++ b/todo.md @@ -27,7 +27,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection` et `VehicleClassification` sont maintenant acceptés par l’API et le scheduler et utilisent le même modèle YOLO COCO, filtré respectivement sur personne (classe 0) et véhicules motorisés (classes 2/3/5/7); les autres types restent refusés tant que leurs algorithmes/modèles ne sont pas implémentés. Tests ciblés Agent 10/10, scheduler PostgreSQL 10/10, scénario d’intégration des deux types 2/2. Compose source jetable `hmd-analysis-1793881315-5ba569` : Agent synthétique enregistré/heartbeaté et caméra assignée; MotionDetection rejeté HTTP 400; jobs personne/véhicule créés, dispatchés, réclamés, complétés et résultats relus via API après persistance PostgreSQL. Tag source dédié supprimé/vérifié absent, teardown zéro conteneur/volume/réseau. Reste : inférence réelle sur flux de caméra synthétique, MotionDetection temporel, reconnaissance faciale/plaque et autres modèles/types, ainsi que validation sur deux Agents déployés. Skill : `skills/analysis-job-pipeline/SKILL.md`. - [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures utilisent un heartbeat vieux de 900 s. Le run PR #276 a validé build/tests et scans des images serveur et Agent. Nouvelle preuve relationnelle locale le 5 novembre 2026 : scénario PostgreSQL deux Agents 1/1; le job réel marque Offline l’Agent périmé, réaffecte la caméra au pair en ligne et conserve les deux lignes d’historique (ancienne libérée, nouvelle active). Compose source `hmd-failover-1793882220-a9bc9c` a laissé tourner le failover Hangfire réel après vieillissement contrôlé du heartbeat; API + PostgreSQL ont confirmé le changement et l’état Offline. Cleanup zéro conteneur/volume/réseau et tag image source dédié supprimé/vérifié absent. La perte d’un Agent déployé, les partitions réseau et la synchronisation multi-hôte restent à mesurer en réel. Skill : `skills/heartbeat-failover/SKILL.md`. -- [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. +- [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, backoff, bail expiré, livraisons différées/déjà prises et routage Hangfire; run PR #332 passé (155 intégration, 35 E2E). Validation simulée locale du 5 novembre : `AppSettingReaderTests` 9/9. Un premier Compose interne a confirmé ntfy mais révélé le mismatch camelCase/minuscules des clés SMTP; `AppSettingReader` normalise maintenant la clé comme l’UI, ce qui corrige aussi les URL AI. Recette source `hmd-notify-mock-1793882996-2efa06` : réglages enregistrés par API, test ntfy HTTP 2xx, test SMTP accepté et message synthétique capturé par Mailpit, sans port publié ni accès externe. Teardown 0 conteneur/volume/réseau; tag Central dédié supprimé/vérifié absent. Restent les essais avec relais SMTP/ntfy réels et appareils destinataires. Livraison at-least-once : panne après acceptation fournisseur mais avant acquittement SQL peut produire un doublon. Skill : `skills/notification-delivery-acceptance/SKILL.md`. - [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé. - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Simulation locale reproductible ajoutée à `scripts/ci/test_ci.py` : faux runtime candidat en échec, code superviseur 75, lien `current` restauré vers v1.0.0, marqueur de mise à jour supprimé; fixture `TemporaryDirectory` détruite automatiquement. Skill : `skills/agent-update-acceptance/SKILL.md`. Restent les validations réelles d’installation, signature, mise à jour et rollback sur hôtes Linux et Windows. -- 2.54.1 From 54eef28f37087cbbe89606851c67259fc426c14c Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 14:13:36 +0100 Subject: [PATCH 26/40] fix(recording): include optional AAC audio in MP4 segments --- skills/agent-runtime-acceptance/SKILL.md | 2 +- skills/backup-restore/SKILL.md | 2 +- skills/camera-access-groups/SKILL.md | 2 +- skills/central-auto-updates/SKILL.md | 4 ++-- skills/compose-disposable-recipe/SKILL.md | 4 +++- skills/deployment-guide-acceptance/SKILL.md | 4 ++-- skills/first-admin-bootstrap/SKILL.md | 2 +- skills/gpu-inference/SKILL.md | 2 +- skills/group-access/SKILL.md | 10 ++++++---- skills/heartbeat-failover/SKILL.md | 4 ++-- skills/heimdall-identity/SKILL.md | 2 +- skills/mdns-camera-discovery/SKILL.md | 2 +- skills/notification-delivery-acceptance/SKILL.md | 2 +- skills/pwa/SKILL.md | 2 +- skills/renovate-automation/SKILL.md | 4 ++-- skills/server-healthchecks/SKILL.md | 2 +- skills/video-recording/SKILL.md | 7 ++++--- skills/webrtc-live/SKILL.md | 11 +++++++---- src/Heimdall.Agent/Services/AgentRecordingService.cs | 3 ++- .../AgentRecordingServiceTests.cs | 6 ++++++ todo.md | 4 ++-- 21 files changed, 48 insertions(+), 33 deletions(-) diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index 97171ca..c39fb33 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -22,7 +22,7 @@ dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-m dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore ``` -For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. Tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source. Serialize Docker acceptance when another source build is using the shared daemon. +For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. If future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon. This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`. diff --git a/skills/backup-restore/SKILL.md b/skills/backup-restore/SKILL.md index 29f0a1b..e37e191 100644 --- a/skills/backup-restore/SKILL.md +++ b/skills/backup-restore/SKILL.md @@ -20,7 +20,7 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res 2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions. 3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions. 4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO. -5. Tear down only the disposable project with `docker compose -p down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files. +5. Install an EXIT cleanup trap before build/start. Tear down only the disposable project with `docker compose -p down --volumes --remove-orphans`; query its Compose project labels and confirm zero containers, volumes, and networks. Remove generated files even on a failed assertion. These fixtures use upstream PostgreSQL/RustFS images and build no local image unless a recipe change explicitly adds one; retain those upstream images. If adding a local build, record its unique tag and remove/verify that exact tag in the same trap after teardown. Never use `--rmi all` or broad prune commands. 6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox). Do not rely on the retired MinIO client download URL. The scripts pass configured S3 credentials explicitly to AWS CLI for each invocation. 7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed. 8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data. diff --git a/skills/camera-access-groups/SKILL.md b/skills/camera-access-groups/SKILL.md index 7d2e0d7..7ffde72 100644 --- a/skills/camera-access-groups/SKILL.md +++ b/skills/camera-access-groups/SKILL.md @@ -16,6 +16,6 @@ When changing this area, verify: - `GroupsPageTests` for site/camera labels and the UI add/remove request sequence. - PostgreSQL integration tests for persistence or query changes; do not use EF InMemory as relational proof. - The disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md` for behavior or deployment changes, using a unique project, network, credentials, ports, and volumes. -- If Compose builds Central from source, override its image with a project-unique tag and remove/verify that exact tag after teardown; retain shared base images. +- If Compose builds Central from source, record a project-unique tag and install an EXIT cleanup trap before build/start. After teardown remove and verify absence of that exact tag even on failure; retain shared base images and report cleanup errors. Use synthetic camera metadata in automated tests. Physical RTSP, snapshot and reconnect behavior is a separate Agent/camera acceptance and must be reported as unverified unless run against real hardware. diff --git a/skills/central-auto-updates/SKILL.md b/skills/central-auto-updates/SKILL.md index 48d6ef1..cd789e3 100644 --- a/skills/central-auto-updates/SKILL.md +++ b/skills/central-auto-updates/SKILL.md @@ -35,6 +35,6 @@ Use this skill when changing the Linux or Windows Central installer, its generat ## Acceptance -Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and scoped teardown. Never connect the recipe to a deployed Docker daemon or production data. +Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data. -If acceptance builds a local Central image, assign a project-unique tag and remove/verify that tag after teardown. Do not remove registry/base images or use broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup. +If acceptance builds a local Central/helper image, record its project-unique tag before build and remove/verify that exact tag in the same cleanup trap, including on failure. Do not remove registry/base images or use `--rmi all` or broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup. diff --git a/skills/compose-disposable-recipe/SKILL.md b/skills/compose-disposable-recipe/SKILL.md index 5a6a02d..9d02d60 100644 --- a/skills/compose-disposable-recipe/SKILL.md +++ b/skills/compose-disposable-recipe/SKILL.md @@ -17,6 +17,8 @@ Use this skill for every Heimdall behavior, deployment, or operational change. R - After teardown, check that the project has no containers, volumes, or networks. For every locally built image tag, run `docker image rm ` if it exists, then verify `docker image inspect ` fails. Remove the temporary Compose override/env/source files. Do not remove shared upstream base images (for example PostgreSQL, .NET SDK, or MediaMTX) or images owned by another recipe/project. - Put teardown and exact-tag image removal in the same cleanup trap so both success and failure paths clean up. Do not reuse another acceptance recipe's locally built image: build a uniquely tagged image for this recipe and remove it in this recipe's cleanup path. - A recipe is not complete until every local application image tag created by that recipe has been removed and verified absent. `docker compose down` does not remove images. Apply this even when the behavioral assertion fails; keep generated upstream/base images and unrelated project images untouched. +- These requirements apply to every Docker-based acceptance recipe, including SDK-only test containers, third-party mocks, one-shot helpers, and failure/partial-build paths. Such recipes must explicitly state whether they build any local images. If they build none, leave upstream images intact and still verify cleanup of project containers, volumes, and networks. If they build any local image (Heimdall or helper), record its unique tag before build and remove/verify it absent in the same `EXIT` cleanup trap, even if Compose startup or the build fails. +- Cleanup must preserve the recipe's original exit status, attempt teardown and removal of every recorded tag independently, and report cleanup failures rather than silently declaring acceptance complete. Never use `--rmi all` because it can remove shared or unrelated images. ## Acceptance workflow @@ -33,6 +35,6 @@ Use this skill for every Heimdall behavior, deployment, or operational change. R 3. Start the minimal Central + PostgreSQL stack from source with `docker compose -p --env-file -f docker/docker-compose.yml -f up -d --build`. 4. Wait for the Central health check and probe the changed behavior through its HTTP/API/UI boundary. Exercise both the expected success path and the relevant rejection/restart path. 5. Capture only sanitized logs or response codes needed to explain a failure. Never print passwords, tokens, connection strings, or full environment files. -6. Tear down the named project and its volumes in a cleanup path. Verify no project containers, volumes, or networks remain. Remove every project-unique image tag created by this recipe and verify it is absent; retain only shared upstream/base images. Delete temporary environment and secret files. +6. Install an `EXIT` trap before the first build/start operation. The trap must preserve the test command's exit status, run `docker compose ... down --volumes --remove-orphans`, verify no project containers/volumes/networks remain, remove every recorded project-unique locally built image tag and verify each is absent, then delete temporary environment, secrets, override, and copied-source files. Attempt each cleanup action even if an earlier cleanup action fails; surface any cleanup failure. Retain shared upstream/base images. Do not use Compose `--rmi all` or broad prune commands. If Docker access is unavailable, request the required local permission or explain the blocker; do not substitute a production deployment or claim the recipe passed. diff --git a/skills/deployment-guide-acceptance/SKILL.md b/skills/deployment-guide-acceptance/SKILL.md index 8c6898d..c192d04 100644 --- a/skills/deployment-guide-acceptance/SKILL.md +++ b/skills/deployment-guide-acceptance/SKILL.md @@ -21,8 +21,8 @@ Read `AGENTS.md`, `todo.md`, `docs/docker-compose.md`, and the relevant Compose 1. Follow the local development installation commands in `docs/docker-compose.md` from the changed checkout. Create a unique project, isolated bridge, generated database/JWT credentials and unused loopback ports under a temporary directory. Do not copy production `.env`, use the default credentials unchanged, or use deployed volumes/networks. 2. Run Compose config validation, build Central from source, start PostgreSQL and Central, then verify PostgreSQL health, Central `/healthz`, bootstrap status, and the documented opt-in default for OCR. 3. When documentation covers OCR enablement, set `PLATE_OCR_ENABLED=true` in the generated temporary env and verify the option reaches the container, then exercise the synthetic crop path. Also verify false by default. Do not infer real camera accuracy. -4. Tear down only the named project with `down --volumes --remove-orphans`; verify zero project containers, volumes, and networks. Remove temporary environment and secret files. -5. Assign the locally built Central image a unique tag containing the project name. After teardown, remove and verify absence of that exact tag. Keep shared upstream runtime/database images and never prune images broadly. +4. Install an EXIT cleanup trap before build/start. Tear down only the named project with `down --volumes --remove-orphans`; verify zero project containers, volumes, and networks. Remove temporary environment and secret files even if build or assertions fail. +5. Record a unique tag for each locally built Central/helper image before build. After teardown, remove and verify absence of each exact tag. Keep shared upstream runtime/database images, preserve test exit status, report cleanup errors, and never use `--rmi all` or prune images broadly. 6. Keep Windows installer execution, production recovery, external S3 services, and real hardware acceptance open unless independently run on those targets. When the Docker daemon is reserved by another acceptance, perform static source/config review and record the Compose run as pending. Never launch an overlapping project to satisfy this recipe. diff --git a/skills/first-admin-bootstrap/SKILL.md b/skills/first-admin-bootstrap/SKILL.md index 6790be6..95ea84a 100644 --- a/skills/first-admin-bootstrap/SKILL.md +++ b/skills/first-admin-bootstrap/SKILL.md @@ -13,6 +13,6 @@ Use this skill when changing account bootstrap, signup, login routing, user crea - Existing installations with users skip setup and keep their accounts. The bootstrap flow must not overwrite or replace existing users. - Update FR/EN resources, route behavior, API client behavior, and tests together. Remove public registration links and ensure direct calls to the old registration route are rejected after setup. - For every implementation change, follow `compose-disposable-recipe` and validate both an empty database (setup and first admin) and an initialized database (setup closed, anonymous registration rejected, admin account creation available). -- Tag every source-built Central image with the unique Compose project name and remove/verify that exact tag after teardown; retain shared PostgreSQL and .NET base images. +- Record a unique tag for every source-built Central image and install an EXIT cleanup trap before build/start. Remove the project and verify zero containers/volumes/networks, then remove and verify absence of each exact local tag even after failure; retain shared PostgreSQL/.NET base images and report cleanup errors. Never use credentials supplied for a real deployment in tests. Use generated credentials in the disposable Compose environment and sanitize logs. diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index 3531b7a..8dc9679 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -22,7 +22,7 @@ Use this skill when changing ONNX Runtime packages, execution provider configura - Add tests for CPU-only selection, successful CUDA selection, missing CUDA provider, and CUDA session initialization failure. Also exercise the repository YOLO fixture with the CPU provider so package changes preserve real inference. - Test the default Agent test suite and the GPU package variant where the local machine permits. GPU package tests may need a larger non-`/tmp` output directory because ONNX GPU and image-processing NuGet packages ship native assets for multiple operating systems. The real-model test searches upward from the test output for `models/yolov8n.onnx`; keep output under the repository or place the fixture alongside the test output. - Any runtime/image or Compose behavior change requires the disposable Compose recipe in `skills/compose-disposable-recipe/SKILL.md`. Keep hardware-only validation open unless NVIDIA, AMD, or Intel hardware is actually exercised. A successful CPU fallback test does not prove GPU execution. -- Tag the locally built CUDA Agent and any Central fixture image with the unique acceptance project name. After stopping the project, remove those exact tags and verify they are absent; retain shared CUDA/runtime base layers and never use `docker image prune`. +- Record unique tags for the locally built CUDA Agent and any Central/helper fixture image before building. Install an EXIT trap before the build/start; after stopping the project, remove each exact local tag independently and verify it is absent, including after failed builds/assertions. Preserve the test exit status and report cleanup errors. Retain shared CUDA/runtime base layers; never use `--rmi all` or `docker image prune`. - The current pinned GPU image pairs ONNX Runtime 1.22 with NVIDIA CUDA 12.8.1/cuDNN 9.8.0.87 on amd64. The CUDA runtime base is pinned by the architecture-specific manifest digest in `docker/Dockerfile.agent.gpu`; the dev overlay targets `linux/amd64` and the Dockerfile uses that target rather than a constant `FROM --platform` override. Refresh the digest only after checking the ONNX Runtime compatibility table and obtaining the matching NVIDIA registry digest. diff --git a/skills/group-access/SKILL.md b/skills/group-access/SKILL.md index f077af8..f7249f9 100644 --- a/skills/group-access/SKILL.md +++ b/skills/group-access/SKILL.md @@ -28,9 +28,11 @@ grant. Soft-deleted groups must stop granting access immediately. project-specific network. Bootstrap the first Admin through the setup API; create a group, add a member using the production route, read the member list, remove the member, and verify the empty list. Use only synthetic data. -3. Tear down that exact project with volumes and orphans, verify there are no - project containers, volumes, or networks, and delete generated secret files. -4. Remove and verify absence of every project-unique locally built image tag - after teardown. Retain shared upstream PostgreSQL/.NET runtime images. +3. Install an EXIT cleanup trap before build/start. Tear down that exact project + with volumes and orphans, verify there are no project containers, volumes, + or networks, remove exact local image tags and verify they are absent, and + delete generated secret files even if an assertion fails. +4. Record each project-unique local image tag before build. Retain shared + upstream PostgreSQL/.NET runtime images; never use `--rmi all` or prune. 5. Update `todo.md` with the exact evidence and keep physical/deployment-only claims separate from local acceptance. diff --git a/skills/heartbeat-failover/SKILL.md b/skills/heartbeat-failover/SKILL.md index 8693d59..081857c 100644 --- a/skills/heartbeat-failover/SKILL.md +++ b/skills/heartbeat-failover/SKILL.md @@ -18,8 +18,8 @@ Read `AGENTS.md`, the Heartbeat/failover item in `todo.md`, `skills/heimdall-dot 1. Run the PostgreSQL tests in `HeartbeatMonitorJobTests`, `AgentFailoverJobTests`, and `CameraAssignmentServiceTests`. 2. Run the integration scenario with two registered Agents: heartbeat both, assign a camera to the source, age only the source heartbeat past the maximum accepted timeout, execute the real `AgentFailoverJob` and `CameraAssignmentService`, then verify the source is Offline, the online peer owns the camera, and both assignment records retain the correct released/active state. -3. Build Central from the changed source in a unique disposable Compose project. Generate database/JWT credentials, use unique loopback ports, network, volumes and image tag, empty Sentry DSN, bootstrap a synthetic admin/site and two synthetic Agents, and assign a synthetic camera. Age the source heartbeat only in the disposable PostgreSQL fixture and let the real Hangfire recurring failover job run; verify the active assignment and historical rows through API/PostgreSQL. -4. Tear down that project with volumes/orphans, verify zero project containers, volumes and networks, then remove and verify absence of the exact source-built Central image tag. Keep upstream Postgres/.NET base images; never run broad image pruning. +3. Before any build/start, install an EXIT cleanup trap. Build Central from the changed source in a unique disposable Compose project. Generate database/JWT credentials, use unique loopback ports, network, volumes and image tag, empty Sentry DSN, bootstrap a synthetic admin/site and two synthetic Agents, and assign a synthetic camera. Age the source heartbeat only in the disposable PostgreSQL fixture and let the real Hangfire recurring failover job run; verify the active assignment and historical rows through API/PostgreSQL. +4. The trap tears down that project with volumes/orphans, verifies zero project containers, volumes and networks, then removes and verifies absence of the exact source-built Central image tag even on failure. Keep upstream Postgres/.NET base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad image pruning. 5. Mark physical Agent loss, network partitions and multi-host timing as unverified unless exercised against deployed Agents. ## Current local evidence diff --git a/skills/heimdall-identity/SKILL.md b/skills/heimdall-identity/SKILL.md index c35211c..21624e0 100644 --- a/skills/heimdall-identity/SKILL.md +++ b/skills/heimdall-identity/SKILL.md @@ -25,6 +25,6 @@ Read `AGENTS.md`, the `AUTH-BOOTSTRAP` entry in `todo.md`, and the Identity wiri - Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility. - For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update `todo.md`, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network. - Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked. -- Give each source-built Central acceptance image a project-unique tag; remove and verify absence of that exact tag after Compose teardown. Keep shared upstream base images and avoid all broad image-prune commands. +- Record a project-unique tag for each source-built Central acceptance image and install an EXIT cleanup trap before build/start. After scoped Compose teardown, verify zero containers/volumes/networks and remove/verify absence of each exact local tag even on failure. Keep shared upstream base images, preserve test exit status, report cleanup failures, and avoid `--rmi all` or broad image-prune commands. Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction). diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md index 34108b8..bbc8823 100644 --- a/skills/mdns-camera-discovery/SKILL.md +++ b/skills/mdns-camera-discovery/SKILL.md @@ -24,6 +24,6 @@ Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL ## Disposable Compose -Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. +Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`. diff --git a/skills/notification-delivery-acceptance/SKILL.md b/skills/notification-delivery-acceptance/SKILL.md index d1ce87c..5dcf776 100644 --- a/skills/notification-delivery-acceptance/SKILL.md +++ b/skills/notification-delivery-acceptance/SKILL.md @@ -19,7 +19,7 @@ Read `AGENTS.md`, PIPE-10/FEAT-05 in `todo.md`, `skills/heimdall-dotnet/SKILL.md 1. Run `AppSettingReaderTests`, notification service/outbox tests, and the PostgreSQL outbox integration tests. 2. Use a disposable Compose project from the changed Central source with PostgreSQL, an isolated ntfy service and Mailpit. Generate database/JWT credentials, use an internal project-only network and no published ports, explicitly empty the Sentry DSN, and keep real SMTP/ntfy credentials out of the environment. 3. Bootstrap a synthetic Admin and save SMTP/ntfy settings through `/api/settings`, matching UI key names. Call `/api/settings/ntfy/test` and `/api/settings/email/test`; verify ntfy returns success and Mailpit stores the synthetic recipient message. -4. Tear down only the project with volumes/orphans, verify zero project containers/volumes/networks, and remove/verify absence of the exact source-built Central image tag. Retain shared ntfy/Mailpit/PostgreSQL/Python base images and never use broad prune commands. +4. Install an EXIT cleanup trap before build/start. Tear down only the project with volumes/orphans, verify zero project containers/volumes/networks, then remove/verify absence of the exact source-built Central image tag even on failure. Retain shared ntfy/Mailpit/PostgreSQL/Python base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or broad prune commands. 5. Report local service acceptance separately from delivery to a real SMTP relay, hosted ntfy server, or user device. ## Current local evidence diff --git a/skills/pwa/SKILL.md b/skills/pwa/SKILL.md index 19c80b4..1d7b151 100644 --- a/skills/pwa/SKILL.md +++ b/skills/pwa/SKILL.md @@ -18,7 +18,7 @@ The supported PWA deployment is at the web origin root (`/`). The Blazor app use ## Acceptance 1. Run `tests/Heimdall.E2E.Tests` with its disposable PostgreSQL fixture and Chromium. Check unauthenticated manifest and icon access, exact public-shell contents, offline navigation fallback, and absence of cached private content. -2. Build the changed source through the disposable Central + PostgreSQL Compose recipe in `skills/compose-disposable-recipe/SKILL.md`; probe `/healthz`, `/manifest.webmanifest`, `/service-worker.js` and the offline page. Use unique project/ports/credentials/volumes and verify teardown. +2. Build the changed source through the disposable Central + PostgreSQL Compose recipe in `skills/compose-disposable-recipe/SKILL.md`; probe `/healthz`, `/manifest.webmanifest`, `/service-worker.js` and the offline page. Use unique project/ports/credentials/volumes and install an EXIT cleanup trap before build/start. Remove the project, verify zero containers/volumes/networks, then remove and verify absence of each exact project-unique local image tag, even after failure; retain shared upstream images and report cleanup errors. Assign the locally built Central image a project-unique tag; remove and verify that exact tag after teardown, while retaining shared .NET/PostgreSQL bases. 3. Review `docs/pwa.md` and deployment instructions for HTTPS, root hosting, reverse proxy/WebSocket support, update and rollback behavior. Report physical iOS/Android/desktop installation, HTTPS proxy, and mobile sleep/network testing only when run on those real environments. 4. Keep the PWA backlog open for validations that require real browsers/devices or remote push infrastructure. Do not claim Web Push exists without a tested VAPID backend, subscriptions, revocation and permission-aware delivery. diff --git a/skills/renovate-automation/SKILL.md b/skills/renovate-automation/SKILL.md index 3ac2af1..66a475a 100644 --- a/skills/renovate-automation/SKILL.md +++ b/skills/renovate-automation/SKILL.md @@ -11,6 +11,6 @@ Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependen - The endpoint must be the HTTPS Gitea API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values. - HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR. - Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials. -- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Remove that exact project and confirm it leaves no containers or volumes; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored. -- The mock-preflight recipe uses a shared upstream Node image and creates no local application image. Retain that base image; if the recipe adds a local build, use a project-unique tag and remove/verify only that exact tag after teardown. +- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Install an EXIT cleanup trap before startup, preserve the test exit status, remove that exact project, and confirm it leaves no containers, volumes, or networks; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored. +- The mock-preflight recipe uses a shared upstream Node image and creates no local images. Retain that base image. If the recipe adds a locally built mock/helper/application image, record its unique tag and remove/verify only that exact tag in the same cleanup trap, including on failure. Do not use `--rmi all` or broad prune commands. - For operational changes, update the P0 Renovate status in `todo.md` with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence. diff --git a/skills/server-healthchecks/SKILL.md b/skills/server-healthchecks/SKILL.md index 76eed22..a8de3aa 100644 --- a/skills/server-healthchecks/SKILL.md +++ b/skills/server-healthchecks/SKILL.md @@ -10,7 +10,7 @@ Use this workflow when changing `Dockerfile` health checks, Central Compose heal - Central and Agent containers probe `/healthz` on port 8080 (the development Agent may bind its host-mapped port). ASP.NET maps this route for `GET`; a `HEAD` request returns 405 and marks a live server unhealthy. - In the Alpine image, use BusyBox `wget` with `-O /dev/null` to issue a GET and discard the body. Do not use `--spider`, because BusyBox implements it as HEAD. - Apply this to both `docker/Dockerfile`/Central Compose and `docker/Dockerfile.agent`/Agent development Compose. Keep the image and Compose probes consistent, with bounded timeout/retries and no published health endpoint required. -- For acceptance, build the changed Central or Agent image from source under a project-unique tag in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy and remove only that project with `down --volumes --remove-orphans`. Verify no labeled containers, volumes, or networks remain, remove and inspect the exact local image tag, and retain shared base images. +- For acceptance, build the changed Central or Agent image from source under a project-unique tag in a unique Compose project with a generated `.env`, synthetic credentials, a loopback-only unused port, and project-scoped volumes/network. Install an EXIT cleanup trap before build/start. Verify a GET health probe succeeds and an equivalent HEAD receives the endpoint's 405; then confirm the changed service reports healthy. In cleanup remove only that project with `down --volumes --remove-orphans`, verify no labeled containers/volumes/networks remain, remove and inspect each exact local image tag even on failure, and retain shared base images. Preserve the test exit status and report cleanup failures. ## Metrics scrape acceptance diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index 041be9a..435c569 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -8,6 +8,7 @@ description: Implement and validate Heimdall Agent video segments, central recor Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses. - Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries. +- Map the primary video stream and optional first audio stream into MP4 segments. Copy compatible video without re-encoding and encode optional audio as AAC at a bounded 128 kbit/s so common RTSP audio codecs are playable in browsers; feeds without audio must still record successfully. Keep privacy/operator consent in the per-camera recording opt-in. - Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port. - Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback. - Central quota is configured with `RECORDING_STORAGE_QUOTA_MAX_BYTES` in Compose (application key `Recordings:StorageQuota:MaxBytes`, default 1 TiB). Options are validated on startup; a segment that would exceed the aggregate persisted recording bytes receives HTTP 507 and its uploaded object is removed. The PostgreSQL advisory transaction lock makes the aggregate check atomic across simultaneous Agent uploads; upload bytes finish before acquiring the short metadata lock. Give each upload attempt a unique object key below its recording ID so a racing idempotent retry cannot overwrite the winning segment; remove the losing attempt's object even when both use the same camera. @@ -15,8 +16,8 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance. - Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. - `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` seeds a manifest and MP4 into a temporary spool, returns 503 then 204 from a mock Central, and proves the segment remains through failure, reuses the same idempotency URL/API-key boundary, and is deleted only after success. -- For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. +- For acceptance, install an EXIT cleanup trap before build/start, then build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. - For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. -- For each recording recipe, use project-unique tags for locally built Central and Agent images, then remove and verify those exact tags after Compose teardown. Retain shared PostgreSQL/MediaMTX base images. Follow `skills/compose-disposable-recipe/SKILL.md`; never use `image prune`. +- For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`. -Current product gaps are audio/event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. +Current product gaps are event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md index d093eb4..ab79ac1 100644 --- a/skills/webrtc-live/SKILL.md +++ b/skills/webrtc-live/SKILL.md @@ -66,9 +66,12 @@ the Agent. Configure its assigned camera against the host loopback RTSP port. Do matching processes/sessions terminate and resource counts return to baseline. 5. Logs and API errors contain no credentials, raw tokens, RTSP URLs, or ICE secrets. Verify configured ICE/TURN candidate behavior separately. -6. Tear down only that Compose project with volumes/orphans, then verify its - containers, volumes and network are gone. Remove and verify absence of the - project-unique Central and Agent image tags built by this recipe. Keep the - shared MediaMTX base image; do not run image-prune commands. +6. Install an EXIT trap before the first image build/start. Tear down only that + Compose project with volumes/orphans, then verify its containers, volumes + and network are gone. Independently remove and verify absence of every + project-unique local image tag built by this recipe (Central, Agent, or + helper), even after a failed build/assertion; preserve shared MediaMTX and + other upstream base images. Preserve the test exit status and report cleanup + failures. Do not use `--rmi all` or broad image-prune commands. Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and the Agent relay test (1/1) pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Physical camera, LAN and external TURN are unvalidated; audio/PTZ remain out of scope, so keep FEAT-01 open. diff --git a/src/Heimdall.Agent/Services/AgentRecordingService.cs b/src/Heimdall.Agent/Services/AgentRecordingService.cs index 647c910..ad0dba2 100644 --- a/src/Heimdall.Agent/Services/AgentRecordingService.cs +++ b/src/Heimdall.Agent/Services/AgentRecordingService.cs @@ -137,7 +137,8 @@ public sealed class AgentRecordingService : BackgroundService foreach (var argument in new[] { "-hide_banner", "-loglevel", "error", "-rtsp_transport", "tcp", "-i", rtspUrl, - "-map", "0:v:0", "-c:v", "copy", "-f", "segment", "-segment_time", + "-map", "0:v:0", "-map", "0:a:0?", "-c:v", "copy", "-c:a", "aac", "-b:a", "128k", + "-f", "segment", "-segment_time", segmentSeconds.ToString(CultureInfo.InvariantCulture), "-segment_format", "mp4", "-reset_timestamps", "1", "-segment_list", Path.Combine(sessionDirectory, "segments.csv"), "-segment_list_type", "csv", "-segment_list_size", "10000", diff --git a/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs index 5bd5a78..09ba9bb 100644 --- a/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs @@ -16,6 +16,12 @@ public sealed class AgentRecordingServiceTests info.FileName.ShouldBe("ffmpeg-test"); info.ArgumentList.ShouldContain(rtsp); + info.ArgumentList.ShouldContain("-map"); + info.ArgumentList.ShouldContain("0:a:0?"); + info.ArgumentList.ShouldContain("-c:a"); + info.ArgumentList.ShouldContain("aac"); + info.ArgumentList.ShouldContain("-b:a"); + info.ArgumentList.ShouldContain("128k"); info.ArgumentList.ShouldContain("-segment_time"); info.ArgumentList.ShouldContain("45"); info.ArgumentList.ShouldContain("-segment_format"); diff --git a/todo.md b/todo.md index 71947c1..284bf58 100644 --- a/todo.md +++ b/todo.md @@ -46,7 +46,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès (2/2 tests Agent ciblés). La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture audio/événementielle et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture déclenchée par événement et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. @@ -56,7 +56,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Le test ciblé HealthControllerTests PostgreSQL est repassé 5/5 le 5 novembre; l’échec réseau/stockage réel reste non validé; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent le scrape Prometheus déployé et les pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. -- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Onze anciens tags d’acceptance ont été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques : bash -n scripts/install/backup, mappings YAML, sources installateurs et git diff --check passés. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir skills/deployment-guide-acceptance/SKILL.md. +- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Le 5 novembre 2026, audit complémentaire : les recipes Docker SDK/mock et les recipes source-build Central/Agent spécifient explicitement le comportement des images et un `EXIT` cleanup trap qui préserve le statut des tests, tente chaque nettoyage, vérifie containers/volumes/réseaux et supprime/vérifie les tags locaux même après échec; aucun `--rmi all`/prune. Modifications documentaires statiques contrôlées par `git diff --check`; aucune nouvelle recette fonctionnelle exécutée (aucun changement comportemental). Onze anciens tags d’acceptance avaient été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques antérieures : bash -n scripts/install/backup, mappings YAML et sources installateurs. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. ## Corrections déjà livrées à préserver -- 2.54.1 From ecd68d1c65484c4f546d241eaaa2e702625a7784 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 14:35:40 +0100 Subject: [PATCH 27/40] fix(privacy): expire plate detection events and snapshots --- skills/vision-identity/SKILL.md | 5 +- .../Jobs/CleanupLicensePlatesJob.cs | 87 +++++++++++- .../CleanupLicensePlatesJobTests.cs | 130 ++++++++++++++++++ .../PlateEventRetentionPostgresTests.cs | 101 ++++++++++++++ todo.md | 2 +- 5 files changed, 319 insertions(+), 6 deletions(-) create mode 100644 tests/Heimdall.Infrastructure.Tests/CleanupLicensePlatesJobTests.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/PlateEventRetentionPostgresTests.cs diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md index 6c2b23a..cc8ab50 100644 --- a/skills/vision-identity/SKILL.md +++ b/skills/vision-identity/SKILL.md @@ -14,7 +14,7 @@ Read `AGENTS.md` and FEAT-03/UI-02 in `todo.md`. Current API contract only suppo - The controller requires a human principal with `Camera.Write`, camera scope, JPEG/PNG signature, configured byte limit (at most 512 KiB), and rate limits. OCR rejects malformed, oversized, or over-4-megapixel crops and times out after a bounded interval. - OCR runs on the Heimdall Central host. The image is written to a random temporary path and deleted in `finally`; do not log the crop, extracted text, embedding, or raw image path. - Store only the normalized plate candidate, confidence, and a `LicensePlateDetected` event. The API may return a unique exact vehicle/person as a suggestion, but it does not persist identity links during OCR. `CameraDetail` presents the suggestion for operator review; the operator must explicitly confirm a vehicle. The confirmation API requires a human principal with both camera and vehicle write permissions, verifies access to the camera, the event-to-observation association, and an exact normalized plate match, and writes the observation/event links together. Never treat OCR output as verified identity. -- OCR observations remain unassigned and use the existing cleanup that purges unassigned plate rows after 30 days. The `LicensePlateDetected` event label and metadata have no equivalent retention in this change, so event retention/privacy review remains open before enabling this in production. +- OCR observations remain unassigned until a human confirms an association; unassigned plate rows are purged after 30 days. `CleanupLicensePlatesJob` also removes `LicensePlateDetected` events older than 30 days, including their label and metadata. If an event has stored snapshots, it deletes those objects from the exact captured destination before deleting the database row. Events with missing/incomplete storage provenance are retained with a warning rather than deleting from a guessed destination. Vehicle-owned plate records remain governed by their explicit vehicle lifecycle. Keep the wider privacy review open before production enablement. ## Face-model gate @@ -44,4 +44,5 @@ Official sources reviewed: 4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. 5. Human confirmation acceptance passed in source-built disposable project `hmd-plate-link-1793880442-bff1ca`: the synthetic OCR crop returned `AB-123-CD` at confidence 0.912; a vehicle with another plate was rejected with HTTP 422; PostgreSQL showed both links null before confirmation; explicit confirmation returned 200 and both `license_plates.VehicleId` and `camera_events.VehicleId` were populated; anonymous confirmation returned 401. Cleanup verified zero containers, volumes and networks and removed/verified absence of the exact `heimdall:hmd-plate-link-1793880442-bff1ca-central` image tag. Two earlier recipe attempts had harness-only readiness/SQL identifier mistakes; each exact project and tag was cleaned and absence checked. 6. Keep assigning the locally built Central image a unique project tag and remove/verify that exact tag on every recipe completion, including failure paths. Retain shared .NET/ASP.NET base images and never use broad image pruning. -7. These acceptances cover one synthetic crop and the API persistence/confirmation path only. They do not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or event retention/privacy suitability. +7. These acceptances cover one synthetic crop and the API persistence/confirmation path only. They do not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or the suitability of the retention period under an external privacy review. +8. Plate-event retention is covered by `CleanupLicensePlatesJobTests` (SQLite: expired plate event removed, recent plate and unrelated events retained; captured snapshot objects removed first; storage deletion failure retains the event) and `PlateEventRetentionPostgresTests` (PostgreSQL EF translation/deletion). The disposable Compose project `hmd-plate-retention-pg-1793885533-16210` ran the PostgreSQL test from the mounted changed source with locked restore, generated credentials, and project-scoped database/NuGet volumes; result 1/1. Teardown removed and verified zero project containers/volumes/networks. The recipe builds no Heimdall image; shared PostgreSQL/SDK base images are retained. This validates the local retention mechanics, not the external privacy policy or any production retention requirement. diff --git a/src/Heimdall.Infrastructure/Jobs/CleanupLicensePlatesJob.cs b/src/Heimdall.Infrastructure/Jobs/CleanupLicensePlatesJob.cs index 3c8d43a..7d7665f 100644 --- a/src/Heimdall.Infrastructure/Jobs/CleanupLicensePlatesJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/CleanupLicensePlatesJob.cs @@ -1,22 +1,30 @@ using Heimdall.Infrastructure.Data; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Jobs; /// -/// CleanupLicensePlatesJob — purge les plaques non associées à un véhicule -/// (VehicleId null) créées il y a plus de 30 jours. Cron : dimanche 6h. +/// Purges unassigned OCR observations and old plate-detection events after 30 days. +/// Event snapshots are removed from their recorded destination before deleting rows. /// public class CleanupLicensePlatesJob { private readonly IDbContextFactory _dbFactory; private readonly ILogger _logger; + private readonly IStorageObjectDeletion? _storage; - public CleanupLicensePlatesJob(IDbContextFactory dbFactory, ILogger logger) + private const int BatchSize = 250; + + public CleanupLicensePlatesJob(IDbContextFactory dbFactory, + ILogger logger, IStorageObjectDeletion? storage = null) { _dbFactory = dbFactory; _logger = logger; + _storage = storage; } public async Task ExecuteAsync(CancellationToken ct) @@ -32,5 +40,78 @@ public class CleanupLicensePlatesJob if (deleted > 0) _logger.LogInformation("License plates cleanup: purged {Count} unassigned plate(s) older than 30 days", deleted); + + var deletedEvents = 0; + DateTime? cursorOccurredAt = null; + var cursorId = Guid.Empty; + while (true) + { + var events = await db.CameraEvents.IgnoreQueryFilters().AsNoTracking() + .Where(e => e.Type == EventType.LicensePlateDetected && e.OccurredAt < cutoff && + (cursorOccurredAt == null || e.OccurredAt > cursorOccurredAt.Value || + (e.OccurredAt == cursorOccurredAt.Value && e.Id.CompareTo(cursorId) > 0))) + .OrderBy(e => e.OccurredAt).ThenBy(e => e.Id) + .Take(BatchSize) + .Select(e => new + { + e.Id, e.OccurredAt, e.SnapshotObjectKey, e.SnapshotThumbObjectKey, + e.SnapshotStorageProvider, e.SnapshotStorageRoot, + e.SnapshotStorageEndpoint, e.SnapshotStorageBucket + }) + .ToListAsync(ct).ConfigureAwait(false); + if (events.Count == 0) break; + cursorOccurredAt = events[^1].OccurredAt; + cursorId = events[^1].Id; + + var deletableIds = new List(events.Count); + var objectsByLocation = new Dictionary>(); + foreach (var item in events) + { + if (item.SnapshotObjectKey is null && item.SnapshotThumbObjectKey is null) + { + deletableIds.Add(item.Id); + continue; + } + + if (item.SnapshotStorageProvider is null) + { + _logger.LogWarning("Retaining expired plate event {EventId}: snapshot destination is not recorded", item.Id); + continue; + } + + var location = new StorageLocation(item.SnapshotStorageProvider.Value, + item.SnapshotStorageRoot, item.SnapshotStorageEndpoint, item.SnapshotStorageBucket); + if (!location.IsComplete) + { + _logger.LogWarning("Retaining expired plate event {EventId}: snapshot destination is incomplete", item.Id); + continue; + } + + if (_storage is null) + { + _logger.LogWarning("Retaining expired plate event {EventId}: snapshot deletion service is unavailable", item.Id); + continue; + } + + if (!objectsByLocation.TryGetValue(location, out var keys)) + objectsByLocation[location] = keys = []; + if (item.SnapshotObjectKey is { } snapshot) keys.Add(snapshot); + if (item.SnapshotThumbObjectKey is { } thumbnail) keys.Add(thumbnail); + deletableIds.Add(item.Id); + } + + // Deleting a row before its exact stored objects succeed can orphan sensitive imagery. + foreach (var (location, keys) in objectsByLocation) + await _storage!.DeleteBatchAsync(keys, location, ct).ConfigureAwait(false); + + if (deletableIds.Count == 0) continue; + deletedEvents += await db.CameraEvents.IgnoreQueryFilters() + .Where(e => deletableIds.Contains(e.Id) && e.Type == EventType.LicensePlateDetected && + e.OccurredAt < cutoff) + .ExecuteDeleteAsync(ct).ConfigureAwait(false); + } + + if (deletedEvents > 0) + _logger.LogInformation("License plate event cleanup: purged {Count} event(s) older than 30 days", deletedEvents); } } diff --git a/tests/Heimdall.Infrastructure.Tests/CleanupLicensePlatesJobTests.cs b/tests/Heimdall.Infrastructure.Tests/CleanupLicensePlatesJobTests.cs new file mode 100644 index 0000000..a07416c --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/CleanupLicensePlatesJobTests.cs @@ -0,0 +1,130 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; +using Heimdall.Infrastructure.Jobs; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +public sealed class CleanupLicensePlatesJobTests : IDisposable +{ + private readonly SqliteConnection _connection = new("DataSource=:memory:"); + private readonly TestDbContextFactory _dbFactory; + private readonly ILogger _logger = Substitute.For>(); + private readonly IStorageObjectDeletion _storage = Substitute.For(); + private readonly Guid _cameraId; + + public CleanupLicensePlatesJobTests() + { + _connection.Open(); + var options = new DbContextOptionsBuilder().UseSqlite(_connection).Options; + using (var db = new AppDbContext(options, new AuditInterceptor())) db.Database.EnsureCreated(); + _dbFactory = new TestDbContextFactory(options); + + using var seed = _dbFactory.CreateDbContext(); + var site = new Site("Retention test site"); + seed.Sites.Add(site); + seed.SaveChangesAsync().GetAwaiter().GetResult(); + var camera = new Camera(site.Id, "Retention test camera", "rtsp://camera.invalid/stream"); + seed.Cameras.Add(camera); + seed.SaveChangesAsync().GetAwaiter().GetResult(); + _cameraId = camera.Id; + } + + [Fact] + public async Task ExecuteAsync_DeletesOnlyExpiredPlateEventsAndKeepsOtherHistory() + { + var expiredPlateEventId = Guid.NewGuid(); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + db.CameraEvents.Add(CreateEvent(EventType.LicensePlateDetected, DateTime.UtcNow.AddDays(-31), "AB-123-CD", expiredPlateEventId)); + db.CameraEvents.Add(CreateEvent(EventType.LicensePlateDetected, DateTime.UtcNow.AddDays(-2), "XY-456-ZZ")); + db.CameraEvents.Add(CreateEvent(EventType.MotionDetected, DateTime.UtcNow.AddDays(-31), "movement")); + await db.SaveChangesAsync(); + } + + await CreateJob().ExecuteAsync(CancellationToken.None); + + await using var verify = await _dbFactory.CreateDbContextAsync(); + var remaining = await verify.CameraEvents.IgnoreQueryFilters().OrderBy(e => e.Type).ToListAsync(); + remaining.Count.ShouldBe(2); + remaining.ShouldNotContain(e => e.Id == expiredPlateEventId); + remaining.ShouldContain(e => e.Type == EventType.LicensePlateDetected && e.Label == "XY-456-ZZ"); + remaining.ShouldContain(e => e.Type == EventType.MotionDetected && e.Label == "movement"); + } + + [Fact] + public async Task ExecuteAsync_DeletesStoredSnapshotsBeforeTheirExpiredPlateEvent() + { + var eventId = Guid.NewGuid(); + const string imageKey = "snapshots/site/camera/event.jpg"; + const string thumbnailKey = "snapshots/site/camera/event.thumb.jpg"; + var location = new StorageLocation(StorageProvider.S3, + S3Endpoint: "https://objects.test", S3Bucket: "heimdall-test"); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + var ev = CreateEvent(EventType.LicensePlateDetected, DateTime.UtcNow.AddDays(-31), "AB-123-CD", eventId); + ev.SetStoredSnapshot(imageKey, location, thumbnailKey); + db.CameraEvents.Add(ev); + await db.SaveChangesAsync(); + } + + await CreateJob().ExecuteAsync(CancellationToken.None); + + await _storage.Received(1).DeleteBatchAsync( + Arg.Is>(keys => keys != null && keys.Contains(imageKey) && keys.Contains(thumbnailKey)), + location, Arg.Any()); + await using var verify = await _dbFactory.CreateDbContextAsync(); + (await verify.CameraEvents.IgnoreQueryFilters().CountAsync(e => e.Id == eventId)).ShouldBe(0); + } + + [Fact] + public async Task ExecuteAsync_KeepsExpiredPlateEventWhenSnapshotDeletionFails() + { + var eventId = Guid.NewGuid(); + var location = new StorageLocation(StorageProvider.Local, LocalRoot: "/synthetic/snapshot-root"); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + var ev = CreateEvent(EventType.LicensePlateDetected, DateTime.UtcNow.AddDays(-31), "AB-123-CD", eventId); + ev.SetStoredSnapshot("snapshots/event.jpg", location); + db.CameraEvents.Add(ev); + await db.SaveChangesAsync(); + } + _storage.DeleteBatchAsync(Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(_ => throw new IOException("synthetic storage failure")); + + await Should.ThrowAsync(() => CreateJob().ExecuteAsync(CancellationToken.None)); + + await using var verify = await _dbFactory.CreateDbContextAsync(); + (await verify.CameraEvents.IgnoreQueryFilters().CountAsync(e => e.Id == eventId)).ShouldBe(1); + } + + private CameraEvent CreateEvent(EventType type, DateTime occurredAt, string label, Guid? id = null) + { + var ev = new CameraEvent(_cameraId, type, 0.9, occurredAt, id); + ev.SetMetadata(label, "{\"plate\":\"AB-123-CD\"}"); + return ev; + } + + private CleanupLicensePlatesJob CreateJob() => new(_dbFactory, _logger, _storage); + + public void Dispose() + { + _connection.Dispose(); + GC.SuppressFinalize(this); + } + + private sealed class TestDbContextFactory(DbContextOptions options) + : IDbContextFactory + { + public AppDbContext CreateDbContext() => new(options, new AuditInterceptor()); + public Task CreateDbContextAsync(CancellationToken cancellationToken = default) + => Task.FromResult(CreateDbContext()); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/PlateEventRetentionPostgresTests.cs b/tests/Heimdall.Infrastructure.Tests/PlateEventRetentionPostgresTests.cs new file mode 100644 index 0000000..a70da2c --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/PlateEventRetentionPostgresTests.cs @@ -0,0 +1,101 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; +using Heimdall.Infrastructure.Jobs; +using Heimdall.TestCommon; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +[Collection("PostgresInfra")] +public sealed class PlateEventRetentionPostgresTests(PostgreSqlContainerFixture postgres) : IAsyncLifetime +{ + private readonly string _database = "plate_retention_" + Guid.NewGuid().ToString("N"); + private NpgsqlConnectionStringBuilder _connection = null!; + private Factory _factory = null!; + private Guid _cameraId; + + public async Task InitializeAsync() + { + await using var admin = new NpgsqlConnection(postgres.ConnectionString); + await admin.OpenAsync(); + await using (var create = new NpgsqlCommand($"CREATE DATABASE {_database}", admin)) + await create.ExecuteNonQueryAsync(); + + _connection = new NpgsqlConnectionStringBuilder(postgres.ConnectionString) + { + Database = _database, + Pooling = false + }; + var options = new DbContextOptionsBuilder().UseNpgsql(_connection.ConnectionString).Options; + _factory = new Factory(options); + await using (var extensionConnection = new NpgsqlConnection(_connection.ConnectionString)) + { + await extensionConnection.OpenAsync(); + await using var extension = new NpgsqlCommand("CREATE EXTENSION IF NOT EXISTS pg_trgm", extensionConnection); + await extension.ExecuteNonQueryAsync(); + } + await using var db = await _factory.CreateDbContextAsync(); + await db.Database.EnsureCreatedAsync(); + var site = new Site("Plate retention site"); + db.Sites.Add(site); + await db.SaveChangesAsync(); + var camera = new Camera(site.Id, "Plate retention camera"); + db.Cameras.Add(camera); + await db.SaveChangesAsync(); + _cameraId = camera.Id; + } + + public async Task DisposeAsync() + { + await using var admin = new NpgsqlConnection(postgres.ConnectionString); + await admin.OpenAsync(); + await using var drop = new NpgsqlCommand($"DROP DATABASE IF EXISTS {_database} WITH (FORCE)", admin); + await drop.ExecuteNonQueryAsync(); + } + + [Fact] + public async Task ExecuteAsync_DeletesExpiredPlateEventsUsingPostgresEfTranslation() + { + var expiredId = Guid.NewGuid(); + var recentId = Guid.NewGuid(); + var motionId = Guid.NewGuid(); + await using (var db = await _factory.CreateDbContextAsync()) + { + db.CameraEvents.AddRange( + CreateEvent(EventType.LicensePlateDetected, DateTime.UtcNow.AddDays(-31), "AB-123-CD", expiredId), + CreateEvent(EventType.LicensePlateDetected, DateTime.UtcNow.AddDays(-2), "XY-456-ZZ", recentId), + CreateEvent(EventType.MotionDetected, DateTime.UtcNow.AddDays(-31), "movement", motionId)); + await db.SaveChangesAsync(); + } + + await new CleanupLicensePlatesJob(_factory, NullLogger.Instance, + Substitute.For()).ExecuteAsync(CancellationToken.None); + + await using var verify = await _factory.CreateDbContextAsync(); + var remaining = await verify.CameraEvents.IgnoreQueryFilters().AsNoTracking().ToListAsync(); + remaining.Select(e => e.Id).ShouldBe(new[] { recentId, motionId }, ignoreOrder: true); + remaining.ShouldContain(e => e.Id == recentId && e.Label == "XY-456-ZZ"); + remaining.ShouldContain(e => e.Id == motionId && e.Label == "movement"); + } + + private CameraEvent CreateEvent(EventType type, DateTime occurredAt, string label, Guid id) + { + var ev = new CameraEvent(_cameraId, type, 0.9, occurredAt, id); + ev.SetMetadata(label, "{\"plate\":\"AB-123-CD\"}"); + return ev; + } + + private sealed class Factory(DbContextOptions options) : IDbContextFactory + { + public AppDbContext CreateDbContext() => new(options, new AuditInterceptor()); + public Task CreateDbContextAsync(CancellationToken cancellationToken = default) + => Task.FromResult(CreateDbContext()); + } +} diff --git a/todo.md b/todo.md index 284bf58..64dbf95 100644 --- a/todo.md +++ b/todo.md @@ -47,7 +47,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture déclenchée par événement et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. -- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); rétention des libellés événements et revue privacy externe. Détails : `skills/vision-identity/SKILL.md`. +- [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. Le 5 novembre 2026, `CleanupLicensePlatesJob` purge aussi après 30 jours les événements `LicensePlateDetected` et leurs snapshots : objets supprimés d’abord sur la destination persistée; événements à provenance absente/incomplète conservés avec warning. Tests SQLite 3/3 couvrent conservation des événements récents/non OCR, suppression des snapshots avant les lignes et maintien de la ligne en cas d’échec storage. Test PostgreSQL de traduction EF et suppression 1/1 dans la recette Compose `hmd-plate-retention-pg-1793885533-16210`; restore locked depuis le source, credentials générés, volumes dédiés, cleanup 0/0/0. La recette ne construit pas d’image Heimdall et conserve les bases Postgres/SDK partagées. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); validation externe de la durée de rétention et revue privacy. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` repassé le 5 novembre après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. -- 2.54.1 From b1a3510d303b18aaf3615559d164846416341e26 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 15:18:51 +0100 Subject: [PATCH 28/40] docs(acceptance): enforce local image cleanup --- skills/compose-disposable-recipe/SKILL.md | 1 + skills/video-recording/SKILL.md | 2 +- todo.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/skills/compose-disposable-recipe/SKILL.md b/skills/compose-disposable-recipe/SKILL.md index 9d02d60..a137853 100644 --- a/skills/compose-disposable-recipe/SKILL.md +++ b/skills/compose-disposable-recipe/SKILL.md @@ -19,6 +19,7 @@ Use this skill for every Heimdall behavior, deployment, or operational change. R - A recipe is not complete until every local application image tag created by that recipe has been removed and verified absent. `docker compose down` does not remove images. Apply this even when the behavioral assertion fails; keep generated upstream/base images and unrelated project images untouched. - These requirements apply to every Docker-based acceptance recipe, including SDK-only test containers, third-party mocks, one-shot helpers, and failure/partial-build paths. Such recipes must explicitly state whether they build any local images. If they build none, leave upstream images intact and still verify cleanup of project containers, volumes, and networks. If they build any local image (Heimdall or helper), record its unique tag before build and remove/verify it absent in the same `EXIT` cleanup trap, even if Compose startup or the build fails. - Cleanup must preserve the recipe's original exit status, attempt teardown and removal of every recorded tag independently, and report cleanup failures rather than silently declaring acceptance complete. Never use `--rmi all` because it can remove shared or unrelated images. +- **Mandatory local image cleanup:** before the first build, enumerate and record every recipe-owned image tag that may be created (application, SDK/test harness, mock, one-shot helper). Use a unique tag for each locally built image. The EXIT trap must remove each exact recorded tag after project teardown and verify it is absent, regardless of whether build, startup, assertions, or teardown failed. Do not count an image as shared merely because its Dockerfile uses a shared base; only remove recipe-built tags, and retain upstream images. If no image is built locally, explicitly say so and verify the project resources are gone. Never leave recipe-created local images behind. ## Acceptance workflow diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index 435c569..1afebf2 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -16,7 +16,7 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance. - Add PostgreSQL tests for migration, metadata/idempotency, quota concurrency/cleanup, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. - `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` seeds a manifest and MP4 into a temporary spool, returns 503 then 204 from a mock Central, and proves the segment remains through failure, reuses the same idempotency URL/API-key boundary, and is deleted only after success. -- For acceptance, install an EXIT cleanup trap before build/start, then build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. +- For acceptance, install an EXIT cleanup trap before build/start, then build Central and Agent from this changed source with unique image tags in a disposable Compose project. Publish a synthetic RTSP stream containing H.264 video and AAC-compatible audio through MediaMTX; register and assign the Agent, enable recording, and prove a segment reaches Central through the live Agent RTSP loop. Verify ffprobe sees video and audio in a downloaded segment, scoped listing/range download, and unauthorized denial. Remove only that Compose project, confirm its containers/volumes/network are gone, and remove/verify every recipe-built local image tag. - For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. - For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`. diff --git a/todo.md b/todo.md index 64dbf95..d419928 100644 --- a/todo.md +++ b/todo.md @@ -46,7 +46,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture déclenchée par événement et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture déclenchée par événement et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. Le 5 novembre 2026, `CleanupLicensePlatesJob` purge aussi après 30 jours les événements `LicensePlateDetected` et leurs snapshots : objets supprimés d’abord sur la destination persistée; événements à provenance absente/incomplète conservés avec warning. Tests SQLite 3/3 couvrent conservation des événements récents/non OCR, suppression des snapshots avant les lignes et maintien de la ligne en cas d’échec storage. Test PostgreSQL de traduction EF et suppression 1/1 dans la recette Compose `hmd-plate-retention-pg-1793885533-16210`; restore locked depuis le source, credentials générés, volumes dédiés, cleanup 0/0/0. La recette ne construit pas d’image Heimdall et conserve les bases Postgres/SDK partagées. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); validation externe de la durée de rétention et revue privacy. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. -- 2.54.1 From e343db1f9bfec324dec8ef94ad3095ddd9dc0460 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 15:19:19 +0100 Subject: [PATCH 29/40] docs(todo): record live recording acceptance --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index d419928..2ce2723 100644 --- a/todo.md +++ b/todo.md @@ -56,7 +56,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Le test ciblé HealthControllerTests PostgreSQL est repassé 5/5 le 5 novembre; l’échec réseau/stockage réel reste non validé; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent le scrape Prometheus déployé et les pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. -- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Le 5 novembre 2026, audit complémentaire : les recipes Docker SDK/mock et les recipes source-build Central/Agent spécifient explicitement le comportement des images et un `EXIT` cleanup trap qui préserve le statut des tests, tente chaque nettoyage, vérifie containers/volumes/réseaux et supprime/vérifie les tags locaux même après échec; aucun `--rmi all`/prune. Modifications documentaires statiques contrôlées par `git diff --check`; aucune nouvelle recette fonctionnelle exécutée (aucun changement comportemental). Onze anciens tags d’acceptance avaient été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques antérieures : bash -n scripts/install/backup, mappings YAML et sources installateurs. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. +- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Le 5 novembre 2026, audit complémentaire : les recipes Docker SDK/mock et les recipes source-build Central/Agent spécifient explicitement le comportement des images et un `EXIT` cleanup trap qui préserve le statut des tests, tente chaque nettoyage, vérifie containers/volumes/réseaux et supprime/vérifie les tags locaux même après échec; aucun `--rmi all`/prune. Modifications documentaires statiques contrôlées par `git diff --check`; recette fonctionnelle FEAT-02 de bout en bout ajoutée le 5 novembre : Central et Agent source-buildés, flux H.264/AAC synthétique, test HTTP Range/anonyme, teardown et retrait des tags vérifiés; voir son entrée détaillée. Onze anciens tags d’acceptance avaient été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques antérieures : bash -n scripts/install/backup, mappings YAML et sources installateurs. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. ## Corrections déjà livrées à préserver -- 2.54.1 From 600e041f5cc93bdac395f24e2fc6e5585a72c7e4 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 16:26:18 +0100 Subject: [PATCH 30/40] feat: enable motion jobs and correct GPU assignment --- skills/analysis-job-pipeline/SKILL.md | 9 ++- skills/camera-assignment/SKILL.md | 17 ++++++ .../Services/AnalysisJobPollingService.cs | 25 +++++++- .../Services/MotionDetectionAnalyzer.cs | 61 +++++++++++++++++++ .../Services/ICameraAssignmentService.cs | 2 +- .../Services/AnalysisJobSchedulerService.cs | 2 +- .../Services/CameraAssignmentService.cs | 23 +++---- .../Controllers/AnalysisJobsController.cs | 4 +- .../AnalysisJobPollingServiceTests.cs | 3 +- .../MotionDetectionAnalyzerTests.cs | 41 +++++++++++++ .../AnalysisJobSchedulerServiceTests.cs | 10 +-- .../CameraAssignmentServiceTests.cs | 23 +++++++ .../Scenarios/AnalysisJobScenarios.cs | 17 +++++- todo.md | 5 +- 14 files changed, 207 insertions(+), 35 deletions(-) create mode 100644 skills/camera-assignment/SKILL.md create mode 100644 src/Heimdall.Agent/Services/MotionDetectionAnalyzer.cs create mode 100644 tests/Heimdall.Agent.Tests/MotionDetectionAnalyzerTests.cs diff --git a/skills/analysis-job-pipeline/SKILL.md b/skills/analysis-job-pipeline/SKILL.md index dbe270e..0b4d037 100644 --- a/skills/analysis-job-pipeline/SKILL.md +++ b/skills/analysis-job-pipeline/SKILL.md @@ -12,13 +12,14 @@ Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet - `ObjectDetection`: return every detection produced by the configured YOLO COCO model. - `PersonDetection`: use the same frame/model path and return only COCO class 0 (`person`). - `VehicleClassification`: use the same frame/model path and return COCO motor-vehicle classes 2 (`car`), 3 (`motorcycle`), 5 (`bus`) and 7 (`truck`). Keep the model label, confidence, box and class index in the result. +- `MotionDetection`: capture two frames from the already active RTSP stream 500 ms apart, downscale both to 32×18, and compare normalized luminance. A changed pixel must differ by at least 0.12; at least 2% changed pixels returns one `motion` detection with changed-region bounds and changed-pixel ratio as confidence. This CPU-only temporal detector does not require the YOLO model; lighting changes and camera shake may produce motion, so tune/measure it against representative cameras before relying on alerts. - The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result. -- Motion detection needs temporal frame comparison; face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection. +- Face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection. - Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types. ## Required validation -1. Unit-test Agent type parsing and the exact COCO class filtering for all three supported types, including empty results and unsupported types. +1. Unit-test Agent type parsing, motion comparison for identical/changed frames, and exact COCO class filtering for the object/person/vehicle types, including empty results and unsupported types. 2. Run PostgreSQL scheduler tests proving CPU/RAM requirements for supported types and refusal of unsupported types. Do not substitute EF InMemory for relational behavior. 3. Run the PostgreSQL integration scenario through the Web API: create each supported job, dispatch to the assigned online Agent, claim it with the Agent API key, submit a result, and verify persisted completion. Verify unsupported type requests receive HTTP 400. 4. Build Central from the changed source in a uniquely tagged disposable Compose project with generated credentials, loopback-only ports, project-owned volumes/network, empty Sentry DSN, and OCR disabled unless the scenario explicitly needs it. Bootstrap synthetic Admin/site/camera, register and heartbeat a synthetic Agent, assign the camera, submit supported and unsupported job types, and verify the lease/result boundary where practical. @@ -27,4 +28,6 @@ Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet ## Current local acceptance evidence -On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections; it does not prove inference from camera frames, MotionDetection, face/plate models, anomaly detection, full-scene analysis, or deployed multi-Agent behavior. +On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference. + +Motion detection implementation and acceptance (5 November 2026): Agent compares two frames 500 ms apart from the active stream at 32×18 luminance; threshold is 0.12 per pixel and 2% changed pixels, and output is one normalized `motion` region. Central API/scheduler accept the type and its 1-core/512-MB/3-minute capability limits. Tests passed: Agent selection/comparison 13/13, PostgreSQL scheduler 27/27, Web/PostgreSQL API contract 3/3. Source-built disposable Compose project `hmd-motion-1793890915-22844` registered a real Agent container, started a synthetic moving RTSP stream, assigned the camera, created a MotionDetection job, and verified the Agent result with label `motion` and normalized bounds persisted in PostgreSQL. The project was torn down and verified at zero containers/volumes/networks; unique Central/Agent tags were removed and verified absent. Camera shake, exposure/lighting changes and representative real-camera thresholds remain unvalidated. diff --git a/skills/camera-assignment/SKILL.md b/skills/camera-assignment/SKILL.md new file mode 100644 index 0000000..124d22b --- /dev/null +++ b/skills/camera-assignment/SKILL.md @@ -0,0 +1,17 @@ +--- +name: camera-assignment +description: Implement and verify assignment of Heimdall cameras to online Agents using persisted assignment history and actual Agent capabilities. +--- + +# Heimdall camera assignment + +Read `AGENTS.md`, the camera/Agent assignment sections of `todo.md`, and `skills/heimdall-dotnet/SKILL.md`. For persistence changes, also follow `skills/ef-core-persistence/SKILL.md`. + +- Keep assignment scoped to the camera's site and online Agents. Persist assignment/release history and update `Camera.AgentId` in the same EF Core unit of work. +- Assignment strategy must use evidence actually supplied by the relevant entity. Do not infer Agent inference hardware from camera-side protocol flags such as PTZ or camera-native motion detection. +- `GpuPriority` prefers Agents reporting `HasGpu`; if none are GPU-capable, it falls back to all online Agents. Workload balancing remains deterministic within the eligible candidates. +- Camera discovery currently does not populate `Camera.HasMotionDetection`; treat that legacy field as unknown/false and do not use it for Agent placement until a camera capability probe supplies verified data. +- Add PostgreSQL relational tests for strategy selection, failover, and assignment history. Do not use EF InMemory to verify concurrency or transaction semantics. +- For every behavior change, build a uniquely tagged disposable Docker Compose acceptance stack from the changed source, exercise the changed assignment through the API or service boundary against PostgreSQL, and use generated credentials, ports, volumes, and project name. Install an EXIT trap before build/start; tear down only that project, verify zero project containers/volumes/networks, remove each locally built image tag and verify it absent. Preserve shared base images and test exit status. Follow `skills/compose-disposable-recipe/SKILL.md`. + +Current validated behavior: `GpuPriority` selects a GPU Agent for a camera even when camera motion capability is false; PostgreSQL test evidence is recorded in `todo.md`. diff --git a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs index 1bee4a1..8ed54ab 100644 --- a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs +++ b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs @@ -88,7 +88,7 @@ public sealed class AnalysisJobPollingService : BackgroundService var camera = _cameras.Cameras.FirstOrDefault(c => c.CameraId == job.CameraId && c.Enabled); if (camera is null || !_streams.IsStreamActive(job.CameraId)) return Failure(job.AttemptId, "Camera is not assigned, enabled, or streaming"); - if (!_analyzer.ModelAvailable) + if (jobType != AnalysisJobType.MotionDetection && !_analyzer.ModelAvailable) return Failure(job.AttemptId, "Object detection model is unavailable"); Snapshot? frame; @@ -103,6 +103,27 @@ public sealed class AnalysisJobPollingService : BackgroundService if (frame is null) return Failure(job.AttemptId, "Camera frame capture failed or timed out"); + if (jobType == AnalysisJobType.MotionDetection) + { + await Task.Delay(TimeSpan.FromMilliseconds(500), ct).ConfigureAwait(false); + Snapshot? nextFrame; + try + { + nextFrame = await _streams.CaptureNextFrameAsync(job.CameraId, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + nextFrame = null; + } + if (nextFrame is null) + return Failure(job.AttemptId, "Camera frame capture failed or timed out"); + + var motion = MotionDetectionAnalyzer.Compare(frame.JpegData, nextFrame.JpegData); + return new AnalysisResult(job.AttemptId, true, null, motion + .Select(d => new AnalysisDetection(d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height, d.ClassIndex)) + .ToArray()); + } + var confidence = TryGetMinConfidence(job.ParametersJson, out var requestedConfidence) ? requestedConfidence : camera.DetectionProfile?.MinConfidence ?? FrameAnalyzerService.DefaultMinConfidence; @@ -184,7 +205,7 @@ public sealed class AnalysisJobPollingService : BackgroundService } private static bool IsSupported(AnalysisJobType type) => type is AnalysisJobType.ObjectDetection or - AnalysisJobType.PersonDetection or AnalysisJobType.VehicleClassification; + AnalysisJobType.PersonDetection or AnalysisJobType.VehicleClassification or AnalysisJobType.MotionDetection; private static AnalysisResult Failure(Guid attemptId, string message) => new(attemptId, false, message, []); diff --git a/src/Heimdall.Agent/Services/MotionDetectionAnalyzer.cs b/src/Heimdall.Agent/Services/MotionDetectionAnalyzer.cs new file mode 100644 index 0000000..1ef4040 --- /dev/null +++ b/src/Heimdall.Agent/Services/MotionDetectionAnalyzer.cs @@ -0,0 +1,61 @@ +using ImageMagick; + +namespace Heimdall.Agent.Services; + +/// Compares two nearby frames at low resolution to detect temporal pixel changes. +internal static class MotionDetectionAnalyzer +{ + private const int Width = 32; + private const int Height = 18; + private const double PixelDifferenceThreshold = 0.12; + private const double ChangedPixelRatioThreshold = 0.02; + + public static DetectionResult[] Compare(byte[] previousJpeg, byte[] currentJpeg) + { + using var previous = Decode(previousJpeg); + using var current = Decode(currentJpeg); + using var previousPixels = previous.GetPixels(); + using var currentPixels = current.GetPixels(); + + var changed = 0; + var minX = Width; + var minY = Height; + var maxX = -1; + var maxY = -1; + for (var y = 0; y < Height; y++) + for (var x = 0; x < Width; x++) + { + var before = Luminance(previousPixels.GetPixel(x, y).ToColor()!); + var after = Luminance(currentPixels.GetPixel(x, y).ToColor()!); + if (Math.Abs(after - before) < PixelDifferenceThreshold) continue; + + changed++; + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x); + maxY = Math.Max(maxY, y); + } + + var ratio = changed / (double)(Width * Height); + if (ratio < ChangedPixelRatioThreshold || maxX < minX || maxY < minY) + return []; + + return + [ + new DetectionResult("motion", (float)Math.Clamp(ratio, 0, 1), + minX / (float)Width, minY / (float)Height, + (maxX - minX + 1) / (float)Width, (maxY - minY + 1) / (float)Height) + ]; + } + + private static MagickImage Decode(byte[] jpeg) + { + var image = new MagickImage(jpeg); + image.Resize(new MagickGeometry(Width, Height) { IgnoreAspectRatio = true }); + image.ColorSpace = ColorSpace.RGB; + return image; + } + + private static double Luminance(IMagickColor color) => + (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / ushort.MaxValue; +} diff --git a/src/Heimdall.Application/Services/ICameraAssignmentService.cs b/src/Heimdall.Application/Services/ICameraAssignmentService.cs index 4c4c466..dbe2572 100644 --- a/src/Heimdall.Application/Services/ICameraAssignmentService.cs +++ b/src/Heimdall.Application/Services/ICameraAssignmentService.cs @@ -8,7 +8,7 @@ public enum AssignmentStrategy { /// Distribute cameras evenly across agents. RoundRobin, - /// Assign detection-heavy cameras to GPU agents first. + /// Prefer online GPU-capable Agents, then balance their camera workload. GpuPriority, /// Assign to the agent with the fewest cameras. LeastCameras, diff --git a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs index 7a39417..b21f010 100644 --- a/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs +++ b/src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs @@ -46,7 +46,7 @@ public sealed class AnalysisJobSchedulerService : IAnalysisJobSchedulerService return ServiceResult.NotFound("Camera not found"); if (jobType is not (AnalysisJobType.ObjectDetection or AnalysisJobType.PersonDetection or - AnalysisJobType.VehicleClassification)) + AnalysisJobType.VehicleClassification or AnalysisJobType.MotionDetection)) return ServiceResult.Failure($"Analysis jobs of type {jobType} are not currently supported"); var job = new AnalysisJob(cameraId, camera.SiteId, jobType, priority, parametersJson); diff --git a/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs b/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs index 4e23923..7f91138 100644 --- a/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs @@ -91,15 +91,10 @@ public sealed class CameraAssignmentService : ICameraAssignmentService var workload = activeAssignments.ToDictionary(x => x.AgentId, x => x.Count); - // Sort cameras by strategy - var orderedCameras = strategy switch - { - AssignmentStrategy.GpuPriority => cameras - .OrderByDescending(c => c.HasMotionDetection) - .ThenByDescending(c => c.Capabilities.HasFlag(CameraCapability.OnvifPtz)) - .ToList(), - _ => cameras.OrderBy(c => c.Name).ToList() - }; + // Camera discovery does not currently report a reliable inference workload + // capability. Keep deterministic ordering and apply GPU priority to actual + // Agent hardware in PickBestAgent rather than protocol flags from the camera. + var orderedCameras = cameras.OrderBy(c => c.Name).ToList(); var assigned = 0; var unassignedCameras = new List(); @@ -128,7 +123,7 @@ public sealed class CameraAssignmentService : ICameraAssignmentService } // Pick the best agent - var bestAgent = PickBestAgent(agents, workload, camera, strategy); + var bestAgent = PickBestAgent(agents, workload, strategy); if (bestAgent is null) { unassignedCameras.Add(camera); @@ -195,7 +190,7 @@ public sealed class CameraAssignmentService : ICameraAssignmentService foreach (var cam in affectedCameras) { - var bestAgent = PickBestAgent(onlineAgents, workload, cam, AssignmentStrategy.Failover); + var bestAgent = PickBestAgent(onlineAgents, workload, AssignmentStrategy.Failover); if (bestAgent is null) { cam.AssignAgent(null); // Waiting; periodic reconciliation retries when an agent returns. @@ -277,16 +272,14 @@ public sealed class CameraAssignmentService : ICameraAssignmentService private static Agent? PickBestAgent( List agents, Dictionary workload, - Camera camera, AssignmentStrategy strategy) { if (agents.Count == 0) return null; var candidates = agents.AsEnumerable(); - // GpuPriority: prefer GPU agents for cameras with detection capabilities - if (strategy == AssignmentStrategy.GpuPriority && - camera.HasMotionDetection) + // GpuPriority: prefer a GPU-capable Agent for every assigned camera. + if (strategy == AssignmentStrategy.GpuPriority) { var gpuAgents = agents.Where(a => a.HasGpu).ToList(); if (gpuAgents.Count > 0) diff --git a/src/Heimdall.Web/Controllers/AnalysisJobsController.cs b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs index 66d63b1..3d14c20 100644 --- a/src/Heimdall.Web/Controllers/AnalysisJobsController.cs +++ b/src/Heimdall.Web/Controllers/AnalysisJobsController.cs @@ -37,8 +37,8 @@ public sealed class AnalysisJobsController( !await access.CameraAsync(requester, cameraId, ct)) return Forbid(); if (!Enum.TryParse(request.JobType, true, out var type) || type is not (AnalysisJobType.ObjectDetection or AnalysisJobType.PersonDetection or - AnalysisJobType.VehicleClassification)) - return BadRequest(new { error = "Supported analysis job types are ObjectDetection, PersonDetection, and VehicleClassification" }); + AnalysisJobType.VehicleClassification or AnalysisJobType.MotionDetection)) + return BadRequest(new { error = "Supported analysis job types are MotionDetection, ObjectDetection, PersonDetection, and VehicleClassification" }); if (request.ParametersJson is { Length: > 16_384 } || !IsValidParameters(request.ParametersJson)) return BadRequest(new { error = "ParametersJson may contain only minConfidence, a number from 0 to 1, and must be at most 16 KiB" }); diff --git a/tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs b/tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs index 7dbc611..8489d68 100644 --- a/tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/AnalysisJobPollingServiceTests.cs @@ -41,9 +41,10 @@ public sealed class AnalysisJobPollingServiceTests [Theory] [InlineData("\"PersonDetection\"", true)] [InlineData("\"vehicLeClassification\"", true)] + [InlineData("\"MotionDetection\"", true)] [InlineData("3", true)] [InlineData("5", true)] - [InlineData("0", false)] + [InlineData("0", true)] [InlineData("\"FaceRecognition\"", false)] [InlineData("\"not-a-job\"", false)] public void SupportedJobTypes_AcceptsOnlyImplementedContracts(string json, bool expected) diff --git a/tests/Heimdall.Agent.Tests/MotionDetectionAnalyzerTests.cs b/tests/Heimdall.Agent.Tests/MotionDetectionAnalyzerTests.cs new file mode 100644 index 0000000..5ff6e49 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/MotionDetectionAnalyzerTests.cs @@ -0,0 +1,41 @@ +using Heimdall.Agent.Services; +using ImageMagick; + +namespace Heimdall.Agent.Tests; + +public sealed class MotionDetectionAnalyzerTests +{ + [Fact] + public void Compare_IdenticalFrames_ReturnsNoMotion() + { + var frame = CreateJpeg(MagickColors.Black); + + MotionDetectionAnalyzer.Compare(frame, frame).ShouldBeEmpty(); + } + + [Fact] + public void Compare_ChangedRegion_ReturnsNormalizedMotionRegion() + { + using var previous = new MagickImage(MagickColors.Black, 320, 180); + using var current = new MagickImage(MagickColors.Black, 320, 180); + using var changedRegion = new MagickImage(MagickColors.White, 160, 90); + current.Composite(changedRegion, 160, 90, CompositeOperator.Over); + + var result = MotionDetectionAnalyzer.Compare( + previous.ToByteArray(MagickFormat.Jpeg), current.ToByteArray(MagickFormat.Jpeg)); + + result.ShouldHaveSingleItem(); + result[0].Label.ShouldBe("motion"); + result[0].Confidence.ShouldBeGreaterThan(0.02f); + result[0].X.ShouldBeGreaterThan(0.45f); + result[0].Y.ShouldBeGreaterThan(0.4f); + result[0].Width.ShouldBeLessThan(0.6f); + result[0].Height.ShouldBeLessThan(0.6f); + } + + private static byte[] CreateJpeg(MagickColor color) + { + using var image = new MagickImage(color, 320, 180); + return image.ToByteArray(MagickFormat.Jpeg); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs index d0bd8fd..de75fa6 100644 --- a/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AnalysisJobSchedulerServiceTests.cs @@ -129,10 +129,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime } [Theory] - [InlineData(AnalysisJobType.PersonDetection, 1024)] - [InlineData(AnalysisJobType.VehicleClassification, 1024)] + [InlineData(AnalysisJobType.PersonDetection, 1024, 2)] + [InlineData(AnalysisJobType.VehicleClassification, 1024, 2)] + [InlineData(AnalysisJobType.MotionDetection, 512, 1)] public async Task CreateJobAsync_SupportedFilteredDetectionTypes_SetsCpuRequirements( - AnalysisJobType type, int memoryMb) + AnalysisJobType type, int memoryMb, int cpuCores) { var (_, cameraId) = await SeedSiteAndCameraAsync(); @@ -141,12 +142,11 @@ public class AnalysisJobSchedulerServiceTests : IAsyncLifetime result.IsSuccess.ShouldBeTrue(); result.Data!.JobType.ShouldBe(type); result.Data.RequiresGpu.ShouldBeFalse(); - result.Data.RequiredCpuCores.ShouldBe(2); + result.Data.RequiredCpuCores.ShouldBe(cpuCores); result.Data.RequiredMemoryMb.ShouldBe(memoryMb); } [Theory] - [InlineData(AnalysisJobType.MotionDetection)] [InlineData(AnalysisJobType.FaceRecognition)] [InlineData(AnalysisJobType.LicensePlateDetection)] [InlineData(AnalysisJobType.AnomalyDetection)] diff --git a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs index 110169f..aae3b3e 100644 --- a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs @@ -142,6 +142,29 @@ public class CameraAssignmentServiceTests : IAsyncLifetime result.IsSuccess.ShouldBeFalse(); } + [Fact] + public async Task AssignSiteCameras_GpuPriority_UsesAgentGpuCapabilityWithoutCameraMotionFlag() + { + var service = new CameraAssignmentService(_dbFactory, _logger); + var (siteId, cpuAgentId, cameraId) = await SeedAsync(); + var gpuAgentId = await SeedAgentAsync(siteId, "agent-gpu"); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + var agent = await db.Agents.FindAsync(gpuAgentId); + agent!.UpdateCapabilities(true, 8, 16384, GpuAcceleration.NvidiaCuda); + var camera = await db.Cameras.FindAsync(cameraId); + camera!.SetCapabilities(ptz: false, audio: false, motion: false); + await db.SaveChangesAsync(); + } + + var result = await service.AssignSiteCamerasAsync(siteId, AssignmentStrategy.GpuPriority, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data.ShouldBe(1); + (await service.GetActiveAssignmentAsync(cameraId, CancellationToken.None))!.AgentId.ShouldBe(gpuAgentId); + gpuAgentId.ShouldNotBe(cpuAgentId); + } + [Fact] public async Task FailoverWithoutReplacement_ClearsAgent_ThenReconcilesOnRecovery() { diff --git a/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs b/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs index 931c2e9..8098e21 100644 --- a/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs +++ b/tests/Heimdall.IntegrationTests/Scenarios/AnalysisJobScenarios.cs @@ -17,6 +17,7 @@ public sealed class AnalysisJobScenarios(PostgreSqlContainerFixture postgres) : [Theory] [InlineData("PersonDetection")] [InlineData("VehicleClassification")] + [InlineData("MotionDetection")] public async Task AnalysisJob_SupportedFilteredDetectionType_IsScheduledAndClaimed(string jobType) { var admin = await Factory.CreateAdminClientAsync(); @@ -40,7 +41,7 @@ public sealed class AnalysisJobScenarios(PostgreSqlContainerFixture postgres) : .StatusCode.ShouldBe(HttpStatusCode.OK); var unsupported = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", - new { jobType = "MotionDetection" }); + new { jobType = "FaceRecognition" }); unsupported.StatusCode.ShouldBe(HttpStatusCode.BadRequest); var created = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", new { jobType }); @@ -59,7 +60,12 @@ public sealed class AnalysisJobScenarios(PostgreSqlContainerFixture postgres) : { attemptId = lease.GetProperty("attemptId").GetGuid(), success = true, - detections = new[] { new { label = jobType == "PersonDetection" ? "person" : "car", + detections = new[] { new { label = jobType switch + { + "PersonDetection" => "person", + "MotionDetection" => "motion", + _ => "car" + }, confidence = 0.93, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } } }); completed.StatusCode.ShouldBe(HttpStatusCode.NoContent); @@ -68,7 +74,12 @@ public sealed class AnalysisJobScenarios(PostgreSqlContainerFixture postgres) : var persistedJob = await persisted.Content.ReadFromJsonAsync(); persistedJob.GetProperty("status").ToString().ShouldBe("Completed"); persistedJob.GetProperty("resultJson").GetString()!.ShouldContain( - jobType == "PersonDetection" ? "person" : "car"); + jobType switch + { + "PersonDetection" => "person", + "MotionDetection" => "motion", + _ => "car" + }); } [Fact] diff --git a/todo.md b/todo.md index 2ce2723..c4ad0bc 100644 --- a/todo.md +++ b/todo.md @@ -25,7 +25,8 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **EF Core / règles de persistance** La PR #116 remplace l’ADO.NET des deux outboxes Agent et du catalogue caméra par EF Core SQLite, préserve les bases locales existantes avec une adoption de schéma testée, et bloque en CI les commandes directes non autorisées. Elle ajoute la skill `skills/ef-core-persistence/`, relie les règles du dépôt au skill et documente les exceptions PostgreSQL spécifiques. Son run PR #390 a passé les tests/builds, les scans serveur/Agent et `CI policy`; fusionnée sur `main` (`9e0eeb8`). - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. -- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection` et `VehicleClassification` sont maintenant acceptés par l’API et le scheduler et utilisent le même modèle YOLO COCO, filtré respectivement sur personne (classe 0) et véhicules motorisés (classes 2/3/5/7); les autres types restent refusés tant que leurs algorithmes/modèles ne sont pas implémentés. Tests ciblés Agent 10/10, scheduler PostgreSQL 10/10, scénario d’intégration des deux types 2/2. Compose source jetable `hmd-analysis-1793881315-5ba569` : Agent synthétique enregistré/heartbeaté et caméra assignée; MotionDetection rejeté HTTP 400; jobs personne/véhicule créés, dispatchés, réclamés, complétés et résultats relus via API après persistance PostgreSQL. Tag source dédié supprimé/vérifié absent, teardown zéro conteneur/volume/réseau. Reste : inférence réelle sur flux de caméra synthétique, MotionDetection temporel, reconnaissance faciale/plaque et autres modèles/types, ainsi que validation sur deux Agents déployés. Skill : `skills/analysis-job-pipeline/SKILL.md`. +- [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection`/`VehicleClassification` réutilisent YOLO COCO et filtrent respectivement la classe personne (0) et les véhicules motorisés (2/3/5/7); `MotionDetection` compare deux frames actives prises à 500 ms d’intervalle (32×18 luminance, différence pixel 0,12, au moins 2 % de pixels modifiés) et renvoie la boîte normalisée du mouvement sans exiger le modèle YOLO. API, scheduler et Agent acceptent ces quatre types; exigences motion : CPU 1, mémoire 512 Mo, timeout 3 min. Tests Agent 13/13, scheduler PostgreSQL 27/27 et intégration API PostgreSQL 3/3. Compose source jetable `hmd-motion-1793890915-22844` : tests, bootstrap Admin/site, inscription Agent, caméra testsrc2 en RTSP affectée, création du job `MotionDetection`, comparaison réelle de frames par Agent et région `motion` relue après persistance. Central/Agent construits avec tags uniques et restore locked; teardown vérifié à 0 conteneur/volume/réseau, tags supprimés et vérifiés absents. Restent : mesure du seuil/bruit sur caméras représentatives, inférence des objets sur frames du flux, détection mouvement native caméra, reconnaissance faciale/plaque, anomalie et analyse de scène, et déploiement multi-Agent réel. Skill : `skills/analysis-job-pipeline/SKILL.md`. +- [x] **Affectation caméra GPU** `GpuPriority` ne s’appuie plus sur `Camera.HasMotionDetection`, indicateur legacy jamais alimenté par la découverte ; cette capacité caméra ne décrit pas le matériel d’inférence de l’Agent. La stratégie préfère maintenant les Agents qui déclarent réellement un GPU et garde l’équilibrage de charge, même lorsque la caméra n’annonce pas de détection mouvement. Recette Compose source jetable `hmd-assign-1793891575-9500` : runner construit avec SDK 10.0.100 et restore locked, PostgreSQL isolé, `CameraAssignmentServiceTests` 10/10 dont le cas GPU; teardown 0 conteneur/volume/réseau et tag `heimdall:hmd-assign-1793891575-9500-tests` retiré/vérifié absent. Après une simplification de signature privée sans changement fonctionnel, le build local repasse mais une relance hors Compose échoue avant les tests car Testcontainers ne démarre pas PostgreSQL dans ce contexte. Les détails d’implémentation et d’acceptation sont dans `skills/camera-assignment/SKILL.md`. La détection fiable des capacités caméra reste à implémenter avant d’utiliser `HasMotionDetection`. - [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures utilisent un heartbeat vieux de 900 s. Le run PR #276 a validé build/tests et scans des images serveur et Agent. Nouvelle preuve relationnelle locale le 5 novembre 2026 : scénario PostgreSQL deux Agents 1/1; le job réel marque Offline l’Agent périmé, réaffecte la caméra au pair en ligne et conserve les deux lignes d’historique (ancienne libérée, nouvelle active). Compose source `hmd-failover-1793882220-a9bc9c` a laissé tourner le failover Hangfire réel après vieillissement contrôlé du heartbeat; API + PostgreSQL ont confirmé le changement et l’état Offline. Cleanup zéro conteneur/volume/réseau et tag image source dédié supprimé/vérifié absent. La perte d’un Agent déployé, les partitions réseau et la synchronisation multi-hôte restent à mesurer en réel. Skill : `skills/heartbeat-failover/SKILL.md`. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, backoff, bail expiré, livraisons différées/déjà prises et routage Hangfire; run PR #332 passé (155 intégration, 35 E2E). Validation simulée locale du 5 novembre : `AppSettingReaderTests` 9/9. Un premier Compose interne a confirmé ntfy mais révélé le mismatch camelCase/minuscules des clés SMTP; `AppSettingReader` normalise maintenant la clé comme l’UI, ce qui corrige aussi les URL AI. Recette source `hmd-notify-mock-1793882996-2efa06` : réglages enregistrés par API, test ntfy HTTP 2xx, test SMTP accepté et message synthétique capturé par Mailpit, sans port publié ni accès externe. Teardown 0 conteneur/volume/réseau; tag Central dédié supprimé/vérifié absent. Restent les essais avec relais SMTP/ntfy réels et appareils destinataires. Livraison at-least-once : panne après acceptation fournisseur mais avant acquittement SQL peut produire un doublon. Skill : `skills/notification-delivery-acceptance/SKILL.md`. - [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé. @@ -56,7 +57,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Le test ciblé HealthControllerTests PostgreSQL est repassé 5/5 le 5 novembre; l’échec réseau/stockage réel reste non validé; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent le scrape Prometheus déployé et les pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. -- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Le 5 novembre 2026, audit complémentaire : les recipes Docker SDK/mock et les recipes source-build Central/Agent spécifient explicitement le comportement des images et un `EXIT` cleanup trap qui préserve le statut des tests, tente chaque nettoyage, vérifie containers/volumes/réseaux et supprime/vérifie les tags locaux même après échec; aucun `--rmi all`/prune. Modifications documentaires statiques contrôlées par `git diff --check`; recette fonctionnelle FEAT-02 de bout en bout ajoutée le 5 novembre : Central et Agent source-buildés, flux H.264/AAC synthétique, test HTTP Range/anonyme, teardown et retrait des tags vérifiés; voir son entrée détaillée. Onze anciens tags d’acceptance avaient été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques antérieures : bash -n scripts/install/backup, mappings YAML et sources installateurs. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. +- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Le 5 novembre 2026, audit complémentaire : les recipes Docker SDK/mock et les recipes source-build Central/Agent spécifient explicitement le comportement des images et un `EXIT` cleanup trap qui préserve le statut des tests, tente chaque nettoyage, vérifie containers/volumes/réseaux et supprime/vérifie les tags locaux même après échec; aucun `--rmi all`/prune. La recette PIPE-01/02 `hmd-motion-1793890915-22844` a également validé en source-built Compose le traitement MotionDetection de frames RTSP synthétiques; teardown et suppression/vérification des tags Central/Agent effectués. Modifications documentaires statiques contrôlées par `git diff --check`; recette fonctionnelle FEAT-02 de bout en bout ajoutée le 5 novembre : Central et Agent source-buildés, flux H.264/AAC synthétique, test HTTP Range/anonyme, teardown et retrait des tags vérifiés; voir son entrée détaillée. Onze anciens tags d’acceptance avaient été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques antérieures : bash -n scripts/install/backup, mappings YAML et sources installateurs. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. ## Corrections déjà livrées à préserver -- 2.54.1 From 8b9352f9444892d54c3cea977077d94ecde58121 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 16:43:36 +0100 Subject: [PATCH 31/40] fix(discovery): persist verified camera ports and capabilities --- skills/mdns-camera-discovery/SKILL.md | 2 + .../Discovery/CameraDiscoveryService.cs | 41 ++++++++++++-- .../Controllers/DiscoveryControllerTests.cs | 53 +++++++++++++++++++ todo.md | 1 + 4 files changed, 93 insertions(+), 4 deletions(-) diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md index bbc8823..de29054 100644 --- a/skills/mdns-camera-discovery/SKILL.md +++ b/skills/mdns-camera-discovery/SKILL.md @@ -13,6 +13,7 @@ Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL - `HomeKitMdnsProbe` maps only categories 17 (camera) and 18 (doorbell) into Agent discovery records. - `NetworkCameraScanner` is the Agent-side source of LAN probes. Preserve HomeKit metadata when its TCP scan has already found the same IP. Central persists and returns metadata; it must not probe the camera LAN. - Resolve an accessory address from an A record attached to the instance or from the exact SRV target hostname. Never use another advertisement's arbitrary A record as a fallback. +- At Central confirmation, persist only capabilities proven by the discovery result and selected stream. Derive RTSP port from the selected RTSP URL (or a probed RTSP port), HTTP port from the HTTP probe, and ONVIF service port from the device-service URL. Do not confuse UDP WS-Discovery port 3702 with the camera's HTTP ONVIF service port. Do not claim PTZ, audio, snapshot, or native motion support unless the probe actually verifies it. ## Synthetic acceptance @@ -21,6 +22,7 @@ Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL - Verify `HomeKitMdnsProbe` maps address/name/id/model/category/pairing/port into its Agent contract, and cancellation yields an empty result. - Run the focused Agent tests and the full Agent test project after changes. - The synthetic packet path validates DNS assembly and mapping only. A disposable Compose test can exercise the Agent source in isolation; only a real camera on a representative LAN validates multicast routing and hardware behavior. Keep that item open until such a run exists. +- The PostgreSQL integration scenario `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` exercises confirmation from discovery metadata through persisted camera fields, including an ONVIF service port distinct from UDP 3702. Preserve that relational coverage when changing confirmation mapping. ## Disposable Compose diff --git a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs index bc080c3..a082fb8 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs @@ -387,10 +387,23 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService request.SubStreamUrl, "[]", 0, 0, 0); } - camera.SetPorts( - discoveryResult.OnvifPort, - discoveryResult.HttpPort, - null); + var rtspPort = GetRtspPort(request.MainStreamUrl, discoveryResult.OpenPorts); + var onvifPort = GetOnvifServicePort(discoveryResult.OnvifDeviceServiceUrl) ?? + (discoveryResult.OnvifPort is > 0 and not 3702 ? discoveryResult.OnvifPort : null); + camera.SetPorts(rtspPort, discoveryResult.HttpPort, onvifPort); + + var capabilities = CameraCapability.None; + if (rtspPort is not null) + capabilities |= CameraCapability.RtspStreaming; + if (onvifPort is not null) + capabilities |= CameraCapability.Onvif; + if (discoveryResult.IsHomeKitCamera == true || discoveryResult.DiscoveryMethod == CameraDiscoveryMethod.MdnsHomeKit) + capabilities |= CameraCapability.HomeKit; + if (discoveryResult.OpenPorts.Contains(37777)) + capabilities |= CameraCapability.Dvrip; + if (!string.IsNullOrWhiteSpace(request.SubStreamUrl)) + capabilities |= CameraCapability.SubStream; + camera.SetCapabilityFlags(capabilities); if (request.Username is not null || request.Password is not null) { @@ -433,6 +446,26 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService return ServiceResult.Success(MapToResponse(camera)); } + private static int? GetRtspPort(string streamUrl, IReadOnlyCollection openPorts) + { + if (Uri.TryCreate(streamUrl, UriKind.Absolute, out var uri) && + (uri.Scheme.Equals("rtsp", StringComparison.OrdinalIgnoreCase) || + uri.Scheme.Equals("rtsps", StringComparison.OrdinalIgnoreCase))) + return uri.Port is > 0 and <= 65535 ? uri.Port : null; + + var discoveredPort = openPorts.FirstOrDefault(port => port is 554 or 8554); + return discoveredPort > 0 ? discoveredPort : null; + } + + private static int? GetOnvifServicePort(string? serviceUrl) + { + if (!Uri.TryCreate(serviceUrl, UriKind.Absolute, out var uri) || + (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + return null; + + return uri.Port is > 0 and <= 65535 ? uri.Port : null; + } + /// Check for duplicate camera before confirming a discovery. public async Task> CheckDuplicateAsync(CheckDuplicateRequest request, CancellationToken ct) { diff --git a/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs index 7dfccd7..63d1525 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs @@ -1,6 +1,10 @@ using System.Net.Http.Json; using System.Text.Json; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; using Heimdall.IntegrationTests.Factories; +using Microsoft.Extensions.DependencyInjection; using Shouldly; namespace Heimdall.IntegrationTests.Controllers; @@ -145,6 +149,55 @@ public class DiscoveryControllerTests : PostgresTestBase response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized); } + [Fact] + public async Task ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities() + { + var admin = await AdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", new { name = "Discovery Ports Site", timezone = "UTC" }); + siteResponse.EnsureSuccessStatusCode(); + var site = await siteResponse.Content.ReadFromJsonAsync(); + var siteId = site.GetProperty("id").GetGuid(); + + var discovery = new CameraDiscoveryResult(siteId, "10.44.0.20"); + discovery.MarkReachable(DetectedCameraType.Standard, CameraDiscoveryMethod.OnvifWsDiscovery); + discovery.SetOpenPorts([554, 3702, 8081]); + discovery.SetHttpResult(8081, 200, "camera-http"); + // 3702 is the ONVIF WS-Discovery UDP probe port; the device service uses 8088. + discovery.SetOnvifResult("http://10.44.0.20:8088/onvif/device_service", "Example", "Model", 3702); + await using (var scope = Factory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.CameraDiscoveryResults.Add(discovery); + await db.SaveChangesAsync(); + } + + var response = await admin.PostAsJsonAsync("api/discovery/confirm", new + { + siteId, + name = "Discovered camera", + discoveryResultId = discovery.Id, + mainStreamUrl = "rtsp://10.44.0.20:8554/primary", + subStreamUrl = "rtsp://10.44.0.20:8555/secondary" + }); + + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var cameraId = (await response.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + await using var verifyScope = Factory.Services.CreateAsyncScope(); + var persisted = await verifyScope.ServiceProvider.GetRequiredService().Cameras.FindAsync(cameraId); + persisted.ShouldNotBeNull(); + persisted!.RtspPort.ShouldBe(8554); + persisted.HttpPort.ShouldBe(8081); + persisted.OnvifPort.ShouldBe(8088); + persisted.Capabilities.HasFlag(CameraCapability.RtspStreaming).ShouldBeTrue(); + persisted.Capabilities.HasFlag(CameraCapability.Onvif).ShouldBeTrue(); + persisted.Capabilities.HasFlag(CameraCapability.SubStream).ShouldBeTrue(); + persisted.Capabilities.HasFlag(CameraCapability.OnvifPtz).ShouldBeFalse(); + persisted.Capabilities.HasFlag(CameraCapability.OnvifAudioIn).ShouldBeFalse(); + persisted.HasPtz.ShouldBeFalse(); + persisted.HasAudio.ShouldBeFalse(); + persisted.HasMotionDetection.ShouldBeFalse(); + } + [Fact] public async Task ProbeIp_RequiresAuth_ReturnsUnauthorized() { diff --git a/todo.md b/todo.md index c4ad0bc..a4c5bfb 100644 --- a/todo.md +++ b/todo.md @@ -24,6 +24,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **EF Core / règles de persistance** La PR #116 remplace l’ADO.NET des deux outboxes Agent et du catalogue caméra par EF Core SQLite, préserve les bases locales existantes avec une adoption de schéma testée, et bloque en CI les commandes directes non autorisées. Elle ajoute la skill `skills/ef-core-persistence/`, relie les règles du dépôt au skill et documente les exceptions PostgreSQL spécifiques. Son run PR #390 a passé les tests/builds, les scans serveur/Agent et `CI policy`; fusionnée sur `main` (`9e0eeb8`). +- [x] **Confirmation découverte caméra** Le mapping de `ConfirmDiscoveryAsync` n’envoie plus le port ONVIF (souvent 3702 UDP) dans `RtspPort` et persiste maintenant le port du service ONVIF tiré de son URL, le port RTSP de l’URL retenue, ainsi que les capacités seulement prouvées (RTSP, ONVIF, HomeKit, DVRIP et sous-flux). PTZ, audio et mouvement natif restent non annoncés sans probe dédié. Test PostgreSQL via API `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` : 1/1; ports 8554/8081/8088 et bitmask vérifiés en base. Compose source-built jetable `hmd-discovery-1793892853-13077`, restore locked avec le digest SDK projet; zéro conteneur/volume/réseau après teardown, tag exact `heimdall:hmd-discovery-1793892853-13077-tests` retiré et vérifié absent. Skill : `skills/mdns-camera-discovery/SKILL.md`. L’acceptation synthétique ne remplace pas un probe ONVIF/PTZ/audio réel. - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection`/`VehicleClassification` réutilisent YOLO COCO et filtrent respectivement la classe personne (0) et les véhicules motorisés (2/3/5/7); `MotionDetection` compare deux frames actives prises à 500 ms d’intervalle (32×18 luminance, différence pixel 0,12, au moins 2 % de pixels modifiés) et renvoie la boîte normalisée du mouvement sans exiger le modèle YOLO. API, scheduler et Agent acceptent ces quatre types; exigences motion : CPU 1, mémoire 512 Mo, timeout 3 min. Tests Agent 13/13, scheduler PostgreSQL 27/27 et intégration API PostgreSQL 3/3. Compose source jetable `hmd-motion-1793890915-22844` : tests, bootstrap Admin/site, inscription Agent, caméra testsrc2 en RTSP affectée, création du job `MotionDetection`, comparaison réelle de frames par Agent et région `motion` relue après persistance. Central/Agent construits avec tags uniques et restore locked; teardown vérifié à 0 conteneur/volume/réseau, tags supprimés et vérifiés absents. Restent : mesure du seuil/bruit sur caméras représentatives, inférence des objets sur frames du flux, détection mouvement native caméra, reconnaissance faciale/plaque, anomalie et analyse de scène, et déploiement multi-Agent réel. Skill : `skills/analysis-job-pipeline/SKILL.md`. - [x] **Affectation caméra GPU** `GpuPriority` ne s’appuie plus sur `Camera.HasMotionDetection`, indicateur legacy jamais alimenté par la découverte ; cette capacité caméra ne décrit pas le matériel d’inférence de l’Agent. La stratégie préfère maintenant les Agents qui déclarent réellement un GPU et garde l’équilibrage de charge, même lorsque la caméra n’annonce pas de détection mouvement. Recette Compose source jetable `hmd-assign-1793891575-9500` : runner construit avec SDK 10.0.100 et restore locked, PostgreSQL isolé, `CameraAssignmentServiceTests` 10/10 dont le cas GPU; teardown 0 conteneur/volume/réseau et tag `heimdall:hmd-assign-1793891575-9500-tests` retiré/vérifié absent. Après une simplification de signature privée sans changement fonctionnel, le build local repasse mais une relance hors Compose échoue avant les tests car Testcontainers ne démarre pas PostgreSQL dans ce contexte. Les détails d’implémentation et d’acceptation sont dans `skills/camera-assignment/SKILL.md`. La détection fiable des capacités caméra reste à implémenter avant d’utiliser `HasMotionDetection`. -- 2.54.1 From 4973c3c455aadb36d8c3d0f3c606c0a992d8eb0d Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 17:02:01 +0100 Subject: [PATCH 32/40] test(discovery): cover default RTSP port mapping --- skills/mdns-camera-discovery/SKILL.md | 2 +- .../Discovery/CameraDiscoveryService.cs | 6 ++++- .../Controllers/DiscoveryControllerTests.cs | 26 +++++++++++++++++++ todo.md | 2 +- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md index de29054..873f292 100644 --- a/skills/mdns-camera-discovery/SKILL.md +++ b/skills/mdns-camera-discovery/SKILL.md @@ -13,7 +13,7 @@ Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL - `HomeKitMdnsProbe` maps only categories 17 (camera) and 18 (doorbell) into Agent discovery records. - `NetworkCameraScanner` is the Agent-side source of LAN probes. Preserve HomeKit metadata when its TCP scan has already found the same IP. Central persists and returns metadata; it must not probe the camera LAN. - Resolve an accessory address from an A record attached to the instance or from the exact SRV target hostname. Never use another advertisement's arbitrary A record as a fallback. -- At Central confirmation, persist only capabilities proven by the discovery result and selected stream. Derive RTSP port from the selected RTSP URL (or a probed RTSP port), HTTP port from the HTTP probe, and ONVIF service port from the device-service URL. Do not confuse UDP WS-Discovery port 3702 with the camera's HTTP ONVIF service port. Do not claim PTZ, audio, snapshot, or native motion support unless the probe actually verifies it. +- At Central confirmation, persist only capabilities proven by the discovery result and selected stream. Derive RTSP port from the selected RTSP URL (554 default for RTSP, 322 for RTSPS when omitted) or a probed RTSP port, HTTP port from the HTTP probe, and ONVIF service port from the device-service URL. Do not confuse UDP WS-Discovery port 3702 with the camera's HTTP ONVIF service port. Do not claim PTZ, audio, snapshot, or native motion support unless the probe actually verifies it. ## Synthetic acceptance diff --git a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs index a082fb8..1a7e7b9 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs @@ -451,7 +451,11 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService if (Uri.TryCreate(streamUrl, UriKind.Absolute, out var uri) && (uri.Scheme.Equals("rtsp", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("rtsps", StringComparison.OrdinalIgnoreCase))) - return uri.Port is > 0 and <= 65535 ? uri.Port : null; + { + if (uri.Port is > 0 and <= 65535) + return uri.Port; + return uri.Scheme.Equals("rtsps", StringComparison.OrdinalIgnoreCase) ? 322 : 554; + } var discoveredPort = openPorts.FirstOrDefault(port => port is 554 or 8554); return discoveredPort > 0 ? discoveredPort : null; diff --git a/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs index 63d1525..d32b9a6 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/DiscoveryControllerTests.cs @@ -196,6 +196,32 @@ public class DiscoveryControllerTests : PostgresTestBase persisted.HasPtz.ShouldBeFalse(); persisted.HasAudio.ShouldBeFalse(); persisted.HasMotionDetection.ShouldBeFalse(); + + var defaultPortDiscovery = new CameraDiscoveryResult(siteId, "10.44.0.21"); + defaultPortDiscovery.MarkReachable(DetectedCameraType.Standard, CameraDiscoveryMethod.NetworkScan); + defaultPortDiscovery.SetOpenPorts([554]); + await using (var scope = Factory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.CameraDiscoveryResults.Add(defaultPortDiscovery); + await db.SaveChangesAsync(); + } + var defaultPortResponse = await admin.PostAsJsonAsync("api/discovery/confirm", new + { + siteId, + name = "Default RTSP camera", + discoveryResultId = defaultPortDiscovery.Id, + mainStreamUrl = "rtsp://10.44.0.21/stream" + }); + defaultPortResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var defaultPortCameraId = (await defaultPortResponse.Content.ReadFromJsonAsync()) + .GetProperty("id").GetGuid(); + await using var defaultVerifyScope = Factory.Services.CreateAsyncScope(); + var defaultPortCamera = await defaultVerifyScope.ServiceProvider.GetRequiredService() + .Cameras.FindAsync(defaultPortCameraId); + defaultPortCamera!.RtspPort.ShouldBe(554); + defaultPortCamera.Capabilities.HasFlag(CameraCapability.RtspStreaming).ShouldBeTrue(); + defaultPortCamera.Capabilities.HasFlag(CameraCapability.Onvif).ShouldBeFalse(); } [Fact] diff --git a/todo.md b/todo.md index a4c5bfb..27abaa1 100644 --- a/todo.md +++ b/todo.md @@ -24,7 +24,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **EF Core / règles de persistance** La PR #116 remplace l’ADO.NET des deux outboxes Agent et du catalogue caméra par EF Core SQLite, préserve les bases locales existantes avec une adoption de schéma testée, et bloque en CI les commandes directes non autorisées. Elle ajoute la skill `skills/ef-core-persistence/`, relie les règles du dépôt au skill et documente les exceptions PostgreSQL spécifiques. Son run PR #390 a passé les tests/builds, les scans serveur/Agent et `CI policy`; fusionnée sur `main` (`9e0eeb8`). -- [x] **Confirmation découverte caméra** Le mapping de `ConfirmDiscoveryAsync` n’envoie plus le port ONVIF (souvent 3702 UDP) dans `RtspPort` et persiste maintenant le port du service ONVIF tiré de son URL, le port RTSP de l’URL retenue, ainsi que les capacités seulement prouvées (RTSP, ONVIF, HomeKit, DVRIP et sous-flux). PTZ, audio et mouvement natif restent non annoncés sans probe dédié. Test PostgreSQL via API `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` : 1/1; ports 8554/8081/8088 et bitmask vérifiés en base. Compose source-built jetable `hmd-discovery-1793892853-13077`, restore locked avec le digest SDK projet; zéro conteneur/volume/réseau après teardown, tag exact `heimdall:hmd-discovery-1793892853-13077-tests` retiré et vérifié absent. Skill : `skills/mdns-camera-discovery/SKILL.md`. L’acceptation synthétique ne remplace pas un probe ONVIF/PTZ/audio réel. +- [x] **Confirmation découverte caméra** Le mapping de `ConfirmDiscoveryAsync` n’envoie plus le port ONVIF (souvent 3702 UDP) dans `RtspPort` et persiste maintenant le port du service ONVIF tiré de son URL, le port RTSP de l’URL retenue, ainsi que les capacités seulement prouvées (RTSP, ONVIF, HomeKit, DVRIP et sous-flux). PTZ, audio et mouvement natif restent non annoncés sans probe dédié. Test PostgreSQL via API `ConfirmDiscovery_PersistsOnlyVerifiedPortsAndCapabilities` : 1/1; ports RTSP personnalisé 8554, HTTP 8081, ONVIF service 8088 et bitmask vérifiés en base; une seconde caméra valide le RTSP standard 554 sans port explicite. Recette Compose jetable `hmd-discovery-port-1793894237-32141` : source montée dans SDK projet épinglé, restore locked depuis cache NuGet local hors réseau, test PostgreSQL 1/1; teardown 0 conteneur/volume/réseau, aucun tag local construit et SDK amont conservé. Skill : `skills/mdns-camera-discovery/SKILL.md`. L’acceptation synthétique ne remplace pas un probe ONVIF/PTZ/audio réel. - [ ] **PIPE-09** La capture manuelle depuis la grille caméra utilise la même API de demande/suivi que la page de détail, actualise la vignette à la fin et conserve les demandes tardives pour les vérifier lors des actualisations suivantes (l'outbox Agent peut livrer après le délai UI). La PR #108 ajoute les tests bUnit de capture terminée et de livraison tardive après expiration UI ; le run PR #323 a passé les 414 tests Web sans test ignoré, les builds et scans serveur/Agent ainsi que `CI policy`. Restent à valider sur caméra réelle les captures automatique/manuelle, corrélation, miniatures, lecture autorisée, reprise d'upload et absence de références cassées. - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l’agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent avec PostgreSQL deux agents, réaffectation après échec, timeout par sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Extension locale du 5 novembre 2026 : `PersonDetection`/`VehicleClassification` réutilisent YOLO COCO et filtrent respectivement la classe personne (0) et les véhicules motorisés (2/3/5/7); `MotionDetection` compare deux frames actives prises à 500 ms d’intervalle (32×18 luminance, différence pixel 0,12, au moins 2 % de pixels modifiés) et renvoie la boîte normalisée du mouvement sans exiger le modèle YOLO. API, scheduler et Agent acceptent ces quatre types; exigences motion : CPU 1, mémoire 512 Mo, timeout 3 min. Tests Agent 13/13, scheduler PostgreSQL 27/27 et intégration API PostgreSQL 3/3. Compose source jetable `hmd-motion-1793890915-22844` : tests, bootstrap Admin/site, inscription Agent, caméra testsrc2 en RTSP affectée, création du job `MotionDetection`, comparaison réelle de frames par Agent et région `motion` relue après persistance. Central/Agent construits avec tags uniques et restore locked; teardown vérifié à 0 conteneur/volume/réseau, tags supprimés et vérifiés absents. Restent : mesure du seuil/bruit sur caméras représentatives, inférence des objets sur frames du flux, détection mouvement native caméra, reconnaissance faciale/plaque, anomalie et analyse de scène, et déploiement multi-Agent réel. Skill : `skills/analysis-job-pipeline/SKILL.md`. - [x] **Affectation caméra GPU** `GpuPriority` ne s’appuie plus sur `Camera.HasMotionDetection`, indicateur legacy jamais alimenté par la découverte ; cette capacité caméra ne décrit pas le matériel d’inférence de l’Agent. La stratégie préfère maintenant les Agents qui déclarent réellement un GPU et garde l’équilibrage de charge, même lorsque la caméra n’annonce pas de détection mouvement. Recette Compose source jetable `hmd-assign-1793891575-9500` : runner construit avec SDK 10.0.100 et restore locked, PostgreSQL isolé, `CameraAssignmentServiceTests` 10/10 dont le cas GPU; teardown 0 conteneur/volume/réseau et tag `heimdall:hmd-assign-1793891575-9500-tests` retiré/vérifié absent. Après une simplification de signature privée sans changement fonctionnel, le build local repasse mais une relance hors Compose échoue avant les tests car Testcontainers ne démarre pas PostgreSQL dans ce contexte. Les détails d’implémentation et d’acceptation sont dans `skills/camera-assignment/SKILL.md`. La détection fiable des capacités caméra reste à implémenter avant d’utiliser `HasMotionDetection`. -- 2.54.1 From bc59d9f90602ccd3df431de2ad0978d3cb2bd381 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 17:16:20 +0100 Subject: [PATCH 33/40] docs(acceptance): require cleanup of local recipe images --- skills/agent-runtime-acceptance/SKILL.md | 2 +- skills/backup-restore/SKILL.md | 2 +- skills/compose-disposable-recipe/SKILL.md | 41 +++++ skills/deployment-guide-acceptance/SKILL.md | 2 +- skills/mdns-camera-discovery/SKILL.md | 2 +- skills/server-healthchecks/SKILL.md | 2 +- skills/video-recording/SKILL.md | 2 + skills/vision-identity/SKILL.md | 4 +- skills/webrtc-live/SKILL.md | 8 +- .../RecordingEventAssociationTests.cs | 164 ++++++++++++++++++ todo.md | 4 +- 11 files changed, 223 insertions(+), 10 deletions(-) create mode 100644 tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index c39fb33..51459ce 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -22,7 +22,7 @@ dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-m dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore ``` -For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. If future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon. +For the focused Kestrel ACK acceptance, copy only the test project's source dependencies into a temporary directory outside the repository. Use a uniquely named Compose project with the pinned .NET SDK image, the temporary source mounted at `/workspace`, a project-scoped NuGet/result volume, a project-scoped bridge, a generated fixture API key, and a loopback-only port. Put the two locked restore/test commands in `/workspace/run-ack-test.sh` and set `entrypoint: ["/bin/bash", "/workspace/run-ack-test.sh"]`; avoid a scalar `command` with `bash -lc`, which Compose passes as multiple arguments and can run `dotnet` without its subcommand. The test itself proves Central returns a transient 503 and then persists the exact digest once. This SDK-only recipe builds no local images; keep the shared upstream SDK image. Install an EXIT cleanup trap before starting, tear down only that project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, and remove the temporary source even on failure. The acceptance record must state `local image tags: none`; if future changes add a local image build, record its unique tag and remove/verify that exact tag in the same trap. Serialize Docker acceptance when another source build is using the shared daemon. This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`. diff --git a/skills/backup-restore/SKILL.md b/skills/backup-restore/SKILL.md index e37e191..cb07bc8 100644 --- a/skills/backup-restore/SKILL.md +++ b/skills/backup-restore/SKILL.md @@ -25,4 +25,4 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res 7. Validate S3 behavior with a disposable RustFS service, unique Compose project/network/volumes and generated keys. Create a synthetic row, run `backup.sh`, verify both dated and `latest.sql.gz` objects, mutate the row, then run `restore.sh --latest --yes` and verify the prior value. Add ancient synthetic daily and weekly keys and confirm both retention jobs delete them. Also exercise `backup-protected-data.sh` upload and `backup-rustfs.sh` mirror/manifest where changed. 8. Keep real-volume production recovery and production RPO/RTO open until validated on their actual service and data. -These backup recipes use shared upstream PostgreSQL/RustFS images and do not build a Heimdall image by default; retain those base images. If a changed recipe adds any local build, tag it uniquely for the Compose project and remove/verify that exact tag after teardown. Do not use image-prune commands. +These backup recipes use shared upstream PostgreSQL/RustFS images and do not build a Heimdall image by default; retain those base images. Record `local image tags: none` for such a run. If a changed recipe adds any local build, tag it uniquely for the Compose project and remove/verify that exact tag after teardown in the same EXIT trap, even on failure. Do not use image-prune commands. diff --git a/skills/compose-disposable-recipe/SKILL.md b/skills/compose-disposable-recipe/SKILL.md index a137853..0717adc 100644 --- a/skills/compose-disposable-recipe/SKILL.md +++ b/skills/compose-disposable-recipe/SKILL.md @@ -21,6 +21,47 @@ Use this skill for every Heimdall behavior, deployment, or operational change. R - Cleanup must preserve the recipe's original exit status, attempt teardown and removal of every recorded tag independently, and report cleanup failures rather than silently declaring acceptance complete. Never use `--rmi all` because it can remove shared or unrelated images. - **Mandatory local image cleanup:** before the first build, enumerate and record every recipe-owned image tag that may be created (application, SDK/test harness, mock, one-shot helper). Use a unique tag for each locally built image. The EXIT trap must remove each exact recorded tag after project teardown and verify it is absent, regardless of whether build, startup, assertions, or teardown failed. Do not count an image as shared merely because its Dockerfile uses a shared base; only remove recipe-built tags, and retain upstream images. If no image is built locally, explicitly say so and verify the project resources are gone. Never leave recipe-created local images behind. +### Required cleanup trap pattern + +Use one `EXIT` trap installed before the first build or Compose start. Record +exact local tags in an array before building; leave the array empty when the +recipe builds no images. Cleanup actions must be independent so a failed +Compose teardown cannot skip image and temporary-file cleanup. Preserve the +original status and return a failure if any cleanup verification fails: + +```bash +cleanup() { + status=$? + trap - EXIT + cleanup_failed=0 + docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \ + down --volumes --remove-orphans || cleanup_failed=1 + # Query all three resource kinds by Compose project label; do not infer + # absence from `compose down`'s exit code alone. + containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 + [[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1 + for tag in "${local_image_tags[@]}"; do + docker image rm "$tag" >/dev/null 2>&1 || true + docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1 + done + rm -rf -- "$temp_dir" || cleanup_failed=1 + if (( cleanup_failed )); then + printf 'Disposable recipe cleanup failed for project %s\\n' "$project" >&2 + status=1 + fi + exit "$status" +} +trap cleanup EXIT +``` + +The label queries must succeed and return empty results for containers, +volumes, and networks. Do not include upstream images in `local_image_tags`. Recipe records must state +the project name, whether local images were built, exact tags and absence +checks (or explicitly “none”), plus project-resource cleanup results. A Docker +recipe that reports teardown without the image-tag check is incomplete. + ## Acceptance workflow 1. Inspect the Compose file and interpolation requirements before starting it. Generate a temporary environment file with unique database/JWT secrets and a distinct loopback port. diff --git a/skills/deployment-guide-acceptance/SKILL.md b/skills/deployment-guide-acceptance/SKILL.md index c192d04..de2a24f 100644 --- a/skills/deployment-guide-acceptance/SKILL.md +++ b/skills/deployment-guide-acceptance/SKILL.md @@ -29,4 +29,4 @@ When the Docker daemon is reserved by another acceptance, perform static source/ ## Latest local attempt -On 5 November 2026, Compose configuration and installer-source assertions passed, but the source build acceptance did not complete: BuildKit's docker-buildx client remained blocked for over eight minutes after its compiler child disappeared, with no project containers created. The command was interrupted; its cleanup trap confirmed zero project containers, volumes, and networks and removed the generated env. A follow-up Compose project hmd-ocr-env-safe-1793874420 reused the previously source-built Central OCR image (the current checkout rebuild was still blocked) to exercise the changed Compose wiring: default PlateOcr__Enabled=false and explicit true after recreate both reported healthy. Sentry__Dsn was explicitly empty. Cleanup verified zero containers, volumes, and networks. An earlier attempt without the Sentry override emitted synthetic EF log events to the configured GlitchTip; no real credentials/data were used. The Compose environment mapping is verified; rebuilding this exact checkout and Windows installer execution remain unverified. pwsh was not installed, so the Windows installer was reviewed statically only. +On 5 November 2026, Compose configuration and installer-source assertions passed, but the source build acceptance did not complete: BuildKit's docker-buildx client remained blocked for over eight minutes after its compiler child disappeared, with no project containers created. The command was interrupted; its cleanup trap confirmed zero project containers, volumes, and networks and removed the generated env. A follow-up Compose project hmd-ocr-env-safe-1793874420 reused the previously source-built Central OCR image (the current checkout rebuild was still blocked) to exercise the changed Compose wiring: default PlateOcr__Enabled=false and explicit true after recreate both reported healthy. Sentry__Dsn was explicitly empty. Cleanup verified zero containers, volumes, and networks. These are partial recipe results: the reused application image was not a uniquely built image for this recipe, and no exact-tag removal/absence check is recorded. Repeat the source build and probe with a fresh project tag before treating deployment-guide Compose acceptance as complete. An earlier attempt without the Sentry override emitted synthetic EF log events to the configured GlitchTip; no real credentials/data were used. The Compose environment mapping is verified; rebuilding this exact checkout and Windows installer execution remain unverified. pwsh was not installed, so the Windows installer was reviewed statically only. diff --git a/skills/mdns-camera-discovery/SKILL.md b/skills/mdns-camera-discovery/SKILL.md index 873f292..1292cb4 100644 --- a/skills/mdns-camera-discovery/SKILL.md +++ b/skills/mdns-camera-discovery/SKILL.md @@ -26,6 +26,6 @@ Read `AGENTS.md`, the mDNS #81 entry in `todo.md`, `skills/heimdall-dotnet/SKILL ## Disposable Compose -Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. +Run a one-shot isolated Compose test from the changed source with the SDK pinned by `global.json` (currently `mcr.microsoft.com/dotnet/sdk:10.0.100`). Copy only the Agent test project and its referenced source projects into a temporary directory outside the repository. Restore with `--locked-mode`, then run only `HomeKitMdnsProbeTests`; these tests synthesize DNS-SD response packets and exercise the parser plus Agent mapping without multicast privileges or access to the LAN. Use a unique Compose project, project-scoped NuGet volume, and isolated bridge; publish no ports and never use host networking. Install an EXIT cleanup trap before starting. This recipe builds no local images: remove only the named project with `down --volumes --remove-orphans`, verify its containers, volumes, and network are gone, then delete the source copy, retaining the shared SDK image. Record `local image tags: none` in the acceptance result. If a future variant builds an app/helper image, tag it uniquely and remove/verify that exact tag in the same cleanup trap. This proves source/test behavior in a container, not multicast delivery or camera discovery on a real LAN. This SDK-only recipe creates no local Heimdall image. Retain the shared SDK base image; if future changes add a local build, use a project-unique tag and remove/verify that exact tag after teardown under `skills/compose-disposable-recipe/SKILL.md`. diff --git a/skills/server-healthchecks/SKILL.md b/skills/server-healthchecks/SKILL.md index a8de3aa..ebc485f 100644 --- a/skills/server-healthchecks/SKILL.md +++ b/skills/server-healthchecks/SKILL.md @@ -16,6 +16,6 @@ Use this workflow when changing `Dockerfile` health checks, Central Compose heal For a Central scrape check, the source-built server image exposes GET /metrics as Prometheus text and includes ASP.NET Core instrumentation after a request. Use the same disposable Compose isolation and an explicitly empty Sentry DSN; scrape the host loopback port, assert HTTP 200 plus Prometheus # HELP/# TYPE and an ASP.NET request metric, then remove the project and verify zero containers, volumes, and networks. Remove and verify absence of that recipe's unique server image tag afterward. -On 5 November 2026, project hmd-metrics-scrape-1793874584 used the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This local check does not validate a deployed Prometheus server or alert thresholds. +On 5 November 2026, project hmd-metrics-scrape-1793874584 reused the prior source-built OCR Central image (no code changes between that image and this scrape). It returned HTTP 200 with Prometheus exposition and ASP.NET metrics; Sentry DSN was empty and teardown verified 0/0/0. This is a partial Docker recipe result: it did not build a unique image for this scrape, so no exact-tag image removal was performed. Repeat the check with a fresh project-unique source-built tag before treating the Docker acceptance as complete. This local check does not validate a deployed Prometheus server or alert thresholds. PostgreSQL readiness regression checks were also rerun locally on 5 November 2026: HealthControllerTests passed 5/5 with the disposable Testcontainers database. The Testcontainers reaper and database stopped after the run; unrelated labeled database services were left untouched. diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index 1afebf2..6d09daa 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -18,6 +18,8 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` seeds a manifest and MP4 into a temporary spool, returns 503 then 204 from a mock Central, and proves the segment remains through failure, reuses the same idempotency URL/API-key boundary, and is deleted only after success. - For acceptance, install an EXIT cleanup trap before build/start, then build Central and Agent from this changed source with unique image tags in a disposable Compose project. Publish a synthetic RTSP stream containing H.264 video and AAC-compatible audio through MediaMTX; register and assign the Agent, enable recording, and prove a segment reaches Central through the live Agent RTSP loop. Verify ffprobe sees video and audio in a downloaded segment, scoped listing/range download, and unauthorized denial. Remove only that Compose project, confirm its containers/volumes/network are gone, and remove/verify every recipe-built local image tag. - For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. +- Run `RecordingEventAssociationTests` against PostgreSQL: upload a segment and verify that only same-camera events in the half-open interval `[timestamp, timestamp + duration)` receive its recording ID; events at either outside boundary remain unlinked. This confirms relational translation and event/recording association without claiming event-triggered capture. - For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`. +- Do not reuse an app/helper tag built by a different acceptance recipe. Build this recipe's changed source under fresh project-unique tags; record `local image tags: none` only for genuinely upstream-only test containers. Every run note must list the exact local tags as absent, or explicitly state no local images were built. Current product gaps are event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md index cc8ab50..03d5108 100644 --- a/skills/vision-identity/SKILL.md +++ b/skills/vision-identity/SKILL.md @@ -39,9 +39,9 @@ Official sources reviewed: ## Acceptance 1. Local targeted tests passed: `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1. These unit/component tests do not replace a browser-driven UI test. -2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. +2. Compose source build passed in isolated project `hmd-plate-20261105094933-31487`. It used a generated database/JWT credential set, unused `127.0.0.1` ports, unique network/image/project, and project-scoped volumes. `PlateOcr` was enabled only through a temporary Compose override. The `synthetic-plate.png` fixture returned `AB-123-CD` with Tesseract confidence `0.912` through the authenticated multipart API; `/api/events` page 1 contained the created event. The historical entry does not record removal and exact-tag absence verification for the image; treat this recipe's image cleanup as unverified and repeat it before relying on that portion of acceptance. 3. The invalid JPEG signature returned HTTP 400. PostgreSQL inspection confirmed the plate observation and history event were persisted with no Person/Vehicle link and no event snapshot. The random OCR temp path was absent after processing. -4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. +4. `down --volumes --remove-orphans` cleanup verified `containers=0 volumes=0 networks=0`. The historical record for this bootstrap does not name a locally built image tag or document an exact image absence check; treat image cleanup as unverified and repeat it before relying on that part of the acceptance. The first admin bootstrap also called the existing HaveIBeenPwned breach checker with a generated synthetic password; that code uses k-anonymity, so the Compose exercise was not fully offline. No real password, camera, image, or release secret was used. 5. Human confirmation acceptance passed in source-built disposable project `hmd-plate-link-1793880442-bff1ca`: the synthetic OCR crop returned `AB-123-CD` at confidence 0.912; a vehicle with another plate was rejected with HTTP 422; PostgreSQL showed both links null before confirmation; explicit confirmation returned 200 and both `license_plates.VehicleId` and `camera_events.VehicleId` were populated; anonymous confirmation returned 401. Cleanup verified zero containers, volumes and networks and removed/verified absence of the exact `heimdall:hmd-plate-link-1793880442-bff1ca-central` image tag. Two earlier recipe attempts had harness-only readiness/SQL identifier mistakes; each exact project and tag was cleaned and absence checked. 6. Keep assigning the locally built Central image a unique project tag and remove/verify that exact tag on every recipe completion, including failure paths. Retain shared .NET/ASP.NET base images and never use broad image pruning. 7. These acceptances cover one synthetic crop and the API persistence/confirmation path only. They do not establish OCR accuracy in real scenes, video plate detection, face recognition, browser-driven upload behavior, camera hardware behavior, or the suitability of the retention period under an external privacy review. diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md index ab79ac1..0ffc9c6 100644 --- a/skills/webrtc-live/SKILL.md +++ b/skills/webrtc-live/SKILL.md @@ -74,4 +74,10 @@ the Agent. Configure its assigned camera against the host loopback RTSP port. Do other upstream base images. Preserve the test exit status and report cleanup failures. Do not use `--rmi all` or broad image-prune commands. -Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and the Agent relay test (1/1) pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Physical camera, LAN and external TURN are unvalidated; audio/PTZ remain out of scope, so keep FEAT-01 open. +For this recipe the locally built tags are Central and Agent; record their +exact project-unique values before building. The synthetic RTSP source uses +the upstream MediaMTX and FFmpeg images, which remain installed. The cleanup +record is complete only after both local tags have been removed and an +exact-tag `docker image inspect` confirms absence. + +Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and the Agent relay test (1/1) pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Its historical record lacks exact-tag image absence checks, so repeat this recipe under the cleanup requirements above before treating cleanup as fully verified. Physical camera, LAN and external TURN are unvalidated; audio/PTZ remain out of scope, so keep FEAT-01 open. diff --git a/tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs b/tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs new file mode 100644 index 0000000..075cccd --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs @@ -0,0 +1,164 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.IntegrationTests.Factories; +using Heimdall.TestCommon; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public sealed class RecordingEventAssociationTests(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres) +{ + private readonly PostgreSqlContainerFixture _postgres = postgres; + + [Fact] + public async Task SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange() + { + if (!_postgres.IsAvailable) return; + + var storage = new TestRecordingStorage(); + await using var factory = new HeimdallWebApplicationFactory(_postgres.ConnectionString, + configureTestServices: services => + { + services.RemoveAll(); + services.AddSingleton(storage); + services.RemoveAll(); + services.AddSingleton(storage); + }); + + var admin = await factory.CreateAdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", new { name = "Recording event site", timezone = "UTC" }); + siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var site = await siteResponse.Content.ReadFromJsonAsync(); + var siteId = site.GetProperty("id").GetGuid(); + var token = site.GetProperty("registrationToken").GetString(); + token.ShouldNotBeNullOrWhiteSpace(); + + var registration = await admin.PostAsJsonAsync("api/agents/register", new + { + token, + hostname = "recording-event-agent", + version = "recording-event-test", + publicIp = (string?)null + }); + registration.StatusCode.ShouldBe(HttpStatusCode.OK); + var agent = await registration.Content.ReadFromJsonAsync(); + var agentId = agent.GetProperty("agentId").GetGuid(); + var apiKey = agent.GetProperty("apiKey").GetString(); + apiKey.ShouldNotBeNullOrWhiteSpace(); + + var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name = "Recording event camera", + rtspUrl = "rtsp://recording-event.invalid/stream", + manufacturer = "test", + model = "test" + }); + cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var camera = await cameraResponse.Content.ReadFromJsonAsync(); + var cameraId = camera.GetProperty("id").GetGuid(); + + var assignment = await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId, reason = "recording-event-test" }); + assignment.StatusCode.ShouldBe(HttpStatusCode.OK); + var enabled = await admin.PutAsJsonAsync($"api/cameras/{cameraId}", new + { + name = "Recording event camera", + rtspUrl = "rtsp://recording-event.invalid/stream", + status = "Online", + recordingEnabled = true + }); + enabled.StatusCode.ShouldBe(HttpStatusCode.OK); + + using var agentClient = factory.CreateClient(); + agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey); + var start = DateTime.UtcNow.AddSeconds(-10); + var eventIds = new Dictionary + { + ["before"] = Guid.NewGuid(), + ["at-start"] = Guid.NewGuid(), + ["inside"] = Guid.NewGuid(), + ["at-end"] = Guid.NewGuid(), + ["after"] = Guid.NewGuid() + }; + foreach (var (name, offset) in new[] + { + ("before", TimeSpan.FromMilliseconds(-1)), + ("at-start", TimeSpan.Zero), + ("inside", TimeSpan.FromMilliseconds(500)), + ("at-end", TimeSpan.FromSeconds(1)), + ("after", TimeSpan.FromMilliseconds(1001)) + }) + { + var reported = await agentClient.PostAsJsonAsync("api/events", new + { + cameraId, + type = (int)EventType.MotionDetected, + confidence = 0.9, + label = name, + metadataJson = (string?)null, + occurredAt = start.Add(offset), + eventId = eventIds[name] + }); + reported.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + var recordingId = Guid.NewGuid(); + using var content = new ByteArrayContent("....ftyp....1234"u8.ToArray()); + content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4"); + var upload = await agentClient.PutAsync( + $"api/cameras/{cameraId}/recordings/{recordingId}/content?timestamp={Uri.EscapeDataString(start.ToString("O"))}&durationSeconds=1", + content); + upload.StatusCode.ShouldBe(HttpStatusCode.OK); + + await using var scope = factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var linkedEvents = await db.CameraEvents.AsNoTracking() + .Where(cameraEvent => eventIds.Values.Contains(cameraEvent.Id)) + .ToDictionaryAsync(cameraEvent => cameraEvent.Label!, cameraEvent => cameraEvent.RecordingId); + linkedEvents["before"].ShouldBeNull(); + linkedEvents["at-start"].ShouldBe(recordingId); + linkedEvents["inside"].ShouldBe(recordingId); + linkedEvents["at-end"].ShouldBeNull(); + linkedEvents["after"].ShouldBeNull(); + storage.ObjectCount.ShouldBe(1); + } + + private sealed class TestRecordingStorage : IRecordingStorage, IStorageObjectDeletion + { + private readonly Dictionary _objects = new(StringComparer.Ordinal); + public int ObjectCount => _objects.Count; + public StorageLocation CaptureCurrentLocation() => new(StorageProvider.Local, LocalRoot: "/event-association-test"); + + public async Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, + CancellationToken ct = default) + { + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + _objects[key] = buffer.ToArray(); + } + + public Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default) + => Task.FromResult(_objects.TryGetValue(key, out var bytes) + ? new MemoryStream(bytes, writable: false) : null); + + public Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, + CancellationToken ct = default) + => Task.FromResult(null); + + public Task DeleteBatchAsync(IReadOnlyCollection keys, StorageLocation location, + CancellationToken ct = default) + { + foreach (var key in keys) _objects.Remove(key); + return Task.CompletedTask; + } + } +} diff --git a/todo.md b/todo.md index 27abaa1..1cf9a06 100644 --- a/todo.md +++ b/todo.md @@ -48,7 +48,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Restent capture déclenchée par événement et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Le 5 novembre, `RecordingEventAssociationTests.SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange` passe 1/1 dans le projet Compose jetable `hmd-recording-event-1793895250-6481` contre PostgreSQL : timestamps avant, au début, dans le segment, à la fin et après; seules les deux occurrences dans `[début, fin)` sont associées. Teardown vérifié 0 conteneur/volume/réseau et aucun tag d’image local; images SDK/PostgreSQL upstream conservées. Restent capture déclenchée par événement et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. Le 5 novembre 2026, `CleanupLicensePlatesJob` purge aussi après 30 jours les événements `LicensePlateDetected` et leurs snapshots : objets supprimés d’abord sur la destination persistée; événements à provenance absente/incomplète conservés avec warning. Tests SQLite 3/3 couvrent conservation des événements récents/non OCR, suppression des snapshots avant les lignes et maintien de la ligne en cas d’échec storage. Test PostgreSQL de traduction EF et suppression 1/1 dans la recette Compose `hmd-plate-retention-pg-1793885533-16210`; restore locked depuis le source, credentials générés, volumes dédiés, cleanup 0/0/0. La recette ne construit pas d’image Heimdall et conserve les bases Postgres/SDK partagées. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); validation externe de la durée de rétention et revue privacy. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. @@ -58,7 +58,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Le test ciblé HealthControllerTests PostgreSQL est repassé 5/5 le 5 novembre; l’échec réseau/stockage réel reste non validé; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent le scrape Prometheus déployé et les pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. -- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in, ses limites et son câblage installateurs, corrige les indications backup obsolètes sur mc, et impose maintenant aux skills de recette des tags d’image uniques supprimés après le teardown, sans image prune ni suppression des bases partagées. Le 5 novembre 2026, audit complémentaire : les recipes Docker SDK/mock et les recipes source-build Central/Agent spécifient explicitement le comportement des images et un `EXIT` cleanup trap qui préserve le statut des tests, tente chaque nettoyage, vérifie containers/volumes/réseaux et supprime/vérifie les tags locaux même après échec; aucun `--rmi all`/prune. La recette PIPE-01/02 `hmd-motion-1793890915-22844` a également validé en source-built Compose le traitement MotionDetection de frames RTSP synthétiques; teardown et suppression/vérification des tags Central/Agent effectués. Modifications documentaires statiques contrôlées par `git diff --check`; recette fonctionnelle FEAT-02 de bout en bout ajoutée le 5 novembre : Central et Agent source-buildés, flux H.264/AAC synthétique, test HTTP Range/anonyme, teardown et retrait des tags vérifiés; voir son entrée détaillée. Onze anciens tags d’acceptance avaient été retirés et vérifiés absents (hmd-plate-*, heimdall:local, heimdall-agent:gpu-local/webrtc-test, tags RBAC/users, hmdbk_a466d0ce-backup:latest et hmdack_8df77197-agent-ack-test:latest). Vérifications statiques antérieures : bash -n scripts/install/backup, mappings YAML et sources installateurs. Le rebuild source Compose est resté bloqué dans BuildKit avant conteneurs; la recette avec l’image Central OCR déjà buildée a ensuite validé par Compose les valeurs effectives false puis true et le healthcheck; teardown confirmé 0/0/0. pwsh absent; Windows et installations distantes non testées. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. +- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in et son câblage installateur, corrige les indications backup obsolètes sur mc, et impose aux skills un `EXIT` cleanup trap préservant le statut des tests, vérifiant les ressources du projet et supprimant/vérifiant chaque tag local exact, même après échec; les images upstream partagées restent intactes, aucun `--rmi all`/prune. Le 5 novembre 2026, les recettes Docker SDK/mock et les recettes source-build Central/Agent ont été auditées; les instructions ont été complétées pour les cas « aucun tag local » et tags locaux. L’audit a aussi rétrogradé les preuves historiques ne documentant pas le contrôle d’absence exact (WebRTC et bootstrap vision) et interdit explicitement de réutiliser un tag d’une autre recette. La validation statique `git diff --check` reste à exécuter pour cette mise à jour. Les acceptations antérieures MotionDetection et FEAT-02 indiquent la suppression/vérification des tags; onze anciens tags d’acceptance avaient également été retirés/vérifiés absents. Les preuves OCR Compose réutilisaient une image locale antérieure et ne remplacent pas un build/tag unique de la recette courante. La fermeture DOC-01 reste ouverte tant que les autres guides et validations externes sont à jour. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. ## Corrections déjà livrées à préserver -- 2.54.1 From edecb601e3cce8fb6c0c58945db30d3e48de414c Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 18:31:11 +0100 Subject: [PATCH 34/40] feat(recordings): add event-triggered camera capture --- skills/video-recording/SKILL.md | 5 +- src/Heimdall.Agent/AgentOptions.cs | 4 + src/Heimdall.Agent/Program.cs | 1 + .../Services/AgentCameraConfig.cs | 3 +- .../Services/AgentRecordingService.cs | 31 +- .../Services/CameraConfigStore.cs | 1 + .../Services/DetectionReporterService.cs | 34 + .../Services/RecordingTriggerStore.cs | 122 + .../CreateCamera/CreateCameraCommand.cs | 2 +- .../ToggleCameraStatusCommand.cs | 2 +- .../UpdateCamera/UpdateCameraCommand.cs | 10 +- .../GetCamera/GetCameraQueryHandler.cs | 2 +- .../GetCamerasBySite/GetCamerasBySiteQuery.cs | 2 +- src/Heimdall.Application/DTOs/CameraDto.cs | 6 +- .../CreateEvent/CreateEventHandler.cs | 11 + .../GetCamerasByGroupQuery.cs | 2 +- .../UploadRecording/UploadRecordingCommand.cs | 4 +- .../GetEffectiveAgentConfigQuery.cs | 1 + src/Heimdall.Domain/Entities/Camera.cs | 3 + .../Configurations/CameraConfiguration.cs | 4 + ...dEventTriggeredCameraRecording.Designer.cs | 2897 +++++++++++++++++ ...162836_AddEventTriggeredCameraRecording.cs | 29 + .../Migrations/AppDbContextModelSnapshot.cs | 5 + .../Components/Pages/CameraDetail.razor | 9 +- .../Controllers/CamerasController.cs | 3 +- .../Localization/SharedResources.en.resx | 6 + .../Localization/SharedResources.fr.resx | 6 + .../Localization/SharedResources.resx | 6 + .../Services/HeimdallApiClient.cs | 6 +- .../CameraConfigStoreTests.cs | 13 + .../DetectionReporterServiceTests.cs | 36 + .../RecordingTriggerStoreTests.cs | 99 + .../Cameras/UpdateCameraHandlerTests.cs | 15 + .../GetEffectiveAgentConfigHandlerTests.cs | 2 + .../RecordingEventAssociationTests.cs | 16 +- .../Components/Pages/CameraDetailTests.cs | 1 + .../HeimdallApiClientCoverageTests.cs | 5 +- todo.md | 4 +- 38 files changed, 3379 insertions(+), 29 deletions(-) create mode 100644 src/Heimdall.Agent/Services/RecordingTriggerStore.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.cs create mode 100644 tests/Heimdall.Agent.Tests/RecordingTriggerStoreTests.cs diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index 6d09daa..a2231ea 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -8,6 +8,7 @@ description: Implement and validate Heimdall Agent video segments, central recor Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses. - Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries. +- Keep continuous recording (`RecordingEnabled`) and event-triggered recording (`EventRecordingEnabled`) as separate per-camera opt-ins. Event mode watches the same active Agent stream, durably records detection trigger windows under the Agent state directory with owner-only permissions, starts FFmpeg on the event, and stops 30 seconds after the latest event by default (`Agent:RecordingEventPostRollSeconds`, validated from 5 to 300 seconds). It does not record pre-roll. Disabling event mode, disabling/removing the camera assignment, or stopping its stream clears pending trigger windows and stops the process. - Map the primary video stream and optional first audio stream into MP4 segments. Copy compatible video without re-encoding and encode optional audio as AAC at a bounded 128 kbit/s so common RTSP audio codecs are playable in browsers; feeds without audio must still record successfully. Keep privacy/operator consent in the per-camera recording opt-in. - Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port. - Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback. @@ -19,7 +20,9 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - For acceptance, install an EXIT cleanup trap before build/start, then build Central and Agent from this changed source with unique image tags in a disposable Compose project. Publish a synthetic RTSP stream containing H.264 video and AAC-compatible audio through MediaMTX; register and assign the Agent, enable recording, and prove a segment reaches Central through the live Agent RTSP loop. Verify ffprobe sees video and audio in a downloaded segment, scoped listing/range download, and unauthorized denial. Remove only that Compose project, confirm its containers/volumes/network are gone, and remove/verify every recipe-built local image tag. - For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. - Run `RecordingEventAssociationTests` against PostgreSQL: upload a segment and verify that only same-camera events in the half-open interval `[timestamp, timestamp + duration)` receive its recording ID; events at either outside boundary remain unlinked. This confirms relational translation and event/recording association without claiming event-triggered capture. +- Event recording is an independent opt-in from continuous recording. Central sends `event_recording_enabled` in the per-Agent camera configuration; the Agent persists one atomic marker per camera, refreshed through the configured post-roll (5–300 seconds, default 30). Motion, person, vehicle, unknown-person, face, and plate events can refresh that window. The Agent starts FFmpeg only while the camera stream is active and the marker remains live. Clear markers when event recording is disabled, the camera is disabled, or assignment is removed. The marker is bounded to one file per camera and survives Agent restart. +- For event-triggered acceptance, enable only `EventRecordingEnabled` through CameraDetail/API, use an assigned Agent and active synthetic RTSP stream, and prove the Agent starts capture and uploads a segment. Verify event association for both event-first and recording-first arrival. Restart the Agent during an active window and prove capture resumes from the marker; disable the toggle and prove uploads stop after configuration settles. Keep real-camera codec and timing validation separate. - For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`. - Do not reuse an app/helper tag built by a different acceptance recipe. Build this recipe's changed source under fresh project-unique tags; record `local image tags: none` only for genuinely upstream-only test containers. Every run note must list the exact local tags as absent, or explicitly state no local images were built. -Current product gaps are event-trigger capture and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. +On 5 November 2026, disposable Compose project `hmd-event-e2e-1793899172-25617` built Central and Agent from this source with locked .NET 10 restore. The actual Agent registered from the generated site token, consumed an animated H.264/AAC RTSP stream, emitted MotionDetected, uploaded an event-only segment while continuous recording remained off, and Central associated the event with that recording. Restarting the Agent while the post-roll marker was active produced another segment; disabling event recording through the API left the recording count stable after configuration settled. PostgreSQL event-first and recording-first association tests both pass. The focused `RecordingTriggerStoreTests` passed 3/3 in SDK Compose project `hmd-trigger-unit-1793899683-6893`. Cleanup traps removed exact local tags `heimdall:hmd-event-e2e-1793899172-25617-central` and `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, verified both absent, and confirmed zero project containers, volumes, and networks; the unit-test recipe built no local images and also left zero project resources. Synthetic motion thresholds were lowered for deterministic event generation. Real-camera codecs/timing remain unvalidated. diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index 98eab52..c70d437 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -55,6 +55,10 @@ public sealed class AgentOptions [Range(5, 300)] public int RecordingSegmentSeconds { get; init; } = 60; + /// Seconds to keep event-triggered capture running after the latest detection. + [Range(5, 300)] + public int RecordingEventPostRollSeconds { get; init; } = 30; + /// Upper bound for queued completed recordings kept locally while Central is unavailable. [Range(typeof(long), "16777216", "107374182400")] public long RecordingSpoolMaxBytes { get; init; } = 1_073_741_824; diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 5185838..d4c4719 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -132,6 +132,7 @@ builder.Services.AddHostedService(sp => sp.GetRequi builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddHostedService(sp => sp.GetRequiredService()); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs index 0603193..3f6d1b4 100644 --- a/src/Heimdall.Agent/Services/AgentCameraConfig.cs +++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs @@ -12,7 +12,8 @@ public sealed record AgentCameraConfig( string? SubRtspUrl, bool Enabled, Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null, - bool RecordingEnabled = false) + bool RecordingEnabled = false, + bool EventRecordingEnabled = false) { /// /// URL used for AI capture: the low-res sub-stream when available, diff --git a/src/Heimdall.Agent/Services/AgentRecordingService.cs b/src/Heimdall.Agent/Services/AgentRecordingService.cs index ad0dba2..3ffdbca 100644 --- a/src/Heimdall.Agent/Services/AgentRecordingService.cs +++ b/src/Heimdall.Agent/Services/AgentRecordingService.cs @@ -21,12 +21,14 @@ public sealed class AgentRecordingService : BackgroundService private readonly AgentOptions _options; private readonly IHttpClientFactory _clients; private readonly ILogger _logger; + private readonly RecordingTriggerStore _triggers; private readonly Dictionary _sessions = []; private readonly SemaphoreSlim _lifecycle = new(1, 1); private string _spoolRoot = string.Empty; public AgentRecordingService(CameraConfigStore cameras, CameraStreamService streams, AgentState state, - IOptions options, IHttpClientFactory clients, ILogger logger) + IOptions options, IHttpClientFactory clients, ILogger logger, + RecordingTriggerStore? triggers = null) { _cameras = cameras; _streams = streams; @@ -34,6 +36,7 @@ public sealed class AgentRecordingService : BackgroundService _options = options.Value; _clients = clients; _logger = logger; + _triggers = triggers ?? new RecordingTriggerStore(options); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) @@ -77,31 +80,45 @@ public sealed class AgentRecordingService : BackgroundService try { var configured = _cameras.Cameras.ToDictionary(c => c.CameraId); + await _triggers.ClearExceptAsync(configured.Values + .Where(camera => camera.Enabled && camera.EventRecordingEnabled) + .Select(camera => camera.CameraId).ToHashSet(), ct).ConfigureAwait(false); foreach (var (cameraId, session) in _sessions.ToArray()) { - if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled || !camera.RecordingEnabled || + if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled || camera.RtspUrl != session.RtspUrl || !_streams.IsStreamActive(cameraId) || session.Process.HasExited) + { + await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false); + continue; + } + if (!camera.RecordingEnabled && !(camera.EventRecordingEnabled && + (await _triggers.GetStatusAsync(cameraId, ct).ConfigureAwait(false)).IsActive)) await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false); } - foreach (var camera in configured.Values.Where(c => c.Enabled && c.RecordingEnabled && + foreach (var camera in configured.Values.Where(c => c.Enabled && + (c.RecordingEnabled || c.EventRecordingEnabled) && !string.IsNullOrWhiteSpace(c.RtspUrl))) { - if (_streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId)) - StartSession(camera); + var triggerStatus = camera.EventRecordingEnabled + ? await _triggers.GetStatusAsync(camera.CameraId, ct).ConfigureAwait(false) + : RecordingTriggerStore.RecordingTriggerStatus.Inactive; + var shouldRecord = camera.RecordingEnabled || triggerStatus.IsActive; + if (shouldRecord && _streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId)) + StartSession(camera, camera.RecordingEnabled ? null : triggerStatus.FirstTriggeredAtUtc); } } finally { _lifecycle.Release(); } } - private void StartSession(AgentCameraConfig camera) + private void StartSession(AgentCameraConfig camera, DateTime? triggeredAtUtc) { var cameraRoot = Path.Combine(_spoolRoot, camera.CameraId.ToString("N")); var sessionDirectory = Path.Combine(cameraRoot, Guid.NewGuid().ToString("N")); Directory.CreateDirectory(sessionDirectory); if (OperatingSystem.IsLinux()) File.SetUnixFileMode(sessionDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - var startedAt = DateTime.UtcNow; + var startedAt = triggeredAtUtc ?? DateTime.UtcNow; File.WriteAllText(Path.Combine(sessionDirectory, "started-at.txt"), startedAt.ToString("O", CultureInfo.InvariantCulture)); var startInfo = CreateStartInfo(_options.RecordingFfmpegPath, camera.RtspUrl!, sessionDirectory, _options.RecordingSegmentSeconds); diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs index fb94add..b48b32b 100644 --- a/src/Heimdall.Agent/Services/CameraConfigStore.cs +++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs @@ -103,6 +103,7 @@ public sealed class CameraConfigStore "sub_rtsp" => existing with { SubRtspUrl = value }, "enabled" => existing with { Enabled = ParseBool(value) }, "recording_enabled" => existing with { RecordingEnabled = ParseBool(value) }, + "event_recording_enabled" => existing with { EventRecordingEnabled = ParseBool(value) }, "profile" => existing with { DetectionProfile = ParseProfile(value) }, _ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field)) }; diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs index 089ce48..f1406f9 100644 --- a/src/Heimdall.Agent/Services/DetectionReporterService.cs +++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs @@ -46,6 +46,8 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo private readonly AgentState _state; private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; + private readonly CameraConfigStore? _cameras; + private readonly RecordingTriggerStore? _recordingTriggers; private readonly string _databasePath; private readonly PooledDbContextFactory _contextFactory; private readonly ConcurrentDictionary<(Guid CameraId, EventType Type), DateTime> _lastQueued = new(); @@ -72,10 +74,23 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo IHttpClientFactory httpClientFactory, ILogger logger, IOptions options) + : this(state, httpClientFactory, logger, options, null, null) + { + } + + public DetectionReporterService( + AgentState state, + IHttpClientFactory httpClientFactory, + ILogger logger, + IOptions options, + CameraConfigStore? cameras, + RecordingTriggerStore? recordingTriggers) { _state = state; _httpClientFactory = httpClientFactory; _logger = logger; + _cameras = cameras; + _recordingTriggers = recordingTriggers; var stateDirectory = options.Value.StateDirectory ?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); _databasePath = Path.Combine(stateDirectory, "agent-events.db"); @@ -118,6 +133,21 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo if (!queued) return false; + if (ShouldTriggerRecording(type) && _cameras?.Cameras.Any(camera => + camera.CameraId == cameraId && camera.EventRecordingEnabled) == true && _recordingTriggers is not null) + { + try + { + await _recordingTriggers.RegisterAsync(cameraId, request.OccurredAt ?? now, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) + { + _logger.LogWarning("Could not persist event recording trigger for camera {CameraId} (error type {ErrorType})", + cameraId, ex.GetType().Name); + } + } + if (type != EventType.ManualSnapshot) _lastQueued[key] = now; try { _wake.Release(); } catch (SemaphoreFullException) { } @@ -438,6 +468,10 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo or System.Net.HttpStatusCode.Gone or System.Net.HttpStatusCode.UnprocessableEntity; + private static bool ShouldTriggerRecording(EventType type) => type is + EventType.MotionDetected or EventType.PersonDetected or EventType.VehicleDetected or + EventType.UnknownPerson or EventType.FaceRecognized or EventType.LicensePlateDetected; + /// Map a detection label to its event category. public static EventType? MapDetectionToEventType(string label) { diff --git a/src/Heimdall.Agent/Services/RecordingTriggerStore.cs b/src/Heimdall.Agent/Services/RecordingTriggerStore.cs new file mode 100644 index 0000000..eaacd3e --- /dev/null +++ b/src/Heimdall.Agent/Services/RecordingTriggerStore.cs @@ -0,0 +1,122 @@ +using System.Text.Json; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Services; + +/// Durable, bounded post-event windows used to start event-only recording after Agent restarts. +public sealed class RecordingTriggerStore : IDisposable +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + private readonly string _root; + private readonly TimeSpan _postRoll; + private readonly SemaphoreSlim _gate = new(1, 1); + + public RecordingTriggerStore(IOptions options) + { + var stateDirectory = options.Value.StateDirectory ?? + (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); + _root = Path.GetFullPath(Path.Combine(stateDirectory, "recording-triggers")); + _postRoll = TimeSpan.FromSeconds(options.Value.RecordingEventPostRollSeconds); + } + + public async Task RegisterAsync(Guid cameraId, DateTime occurredAt, CancellationToken ct = default) + { + if (cameraId == Guid.Empty) throw new ArgumentException("Camera ID is required", nameof(cameraId)); + var normalizedOccurredAt = CameraEvent.NormalizeOccurredAt(occurredAt); + var directory = Path.Combine(_root, cameraId.ToString("N")); + var path = Path.Combine(directory, "trigger.json"); + var temporaryPath = Path.Combine(directory, "trigger.json.tmp"); + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + Directory.CreateDirectory(directory); + if (OperatingSystem.IsLinux()) + { + File.SetUnixFileMode(_root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + File.SetUnixFileMode(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + var previous = await ReadTriggerAsync(path, ct).ConfigureAwait(false); + var trigger = new RecordingTrigger( + previous is { } existing && existing.ExpiresAtUtc > DateTime.UtcNow + ? Min(existing.OccurredAtUtc, normalizedOccurredAt) + : normalizedOccurredAt, + DateTime.UtcNow.Add(_postRoll)); + await using (var stream = new FileStream(temporaryPath, FileMode.Create, FileAccess.Write, + FileShare.None, 4096, FileOptions.Asynchronous | FileOptions.WriteThrough)) + await JsonSerializer.SerializeAsync(stream, trigger, Json, ct).ConfigureAwait(false); + File.Move(temporaryPath, path, overwrite: true); + } + finally + { + if (File.Exists(temporaryPath)) File.Delete(temporaryPath); + _gate.Release(); + } + } + + public async Task GetStatusAsync(Guid cameraId, CancellationToken ct = default) + { + var directory = Path.Combine(_root, cameraId.ToString("N")); + if (!Directory.Exists(directory)) return RecordingTriggerStatus.Inactive; + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + var now = DateTime.UtcNow; + var path = Path.Combine(directory, "trigger.json"); + var trigger = await ReadTriggerAsync(path, ct).ConfigureAwait(false); + if (trigger is null || trigger.ExpiresAtUtc <= now) + { + try { File.Delete(path); } + catch (IOException) { } + return RecordingTriggerStatus.Inactive; + } + return new RecordingTriggerStatus(trigger.OccurredAtUtc, trigger.ExpiresAtUtc); + } + finally { _gate.Release(); } + } + + private static async Task ReadTriggerAsync(string path, CancellationToken ct) + { + if (!File.Exists(path)) return null; + try + { + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, + 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); + return await JsonSerializer.DeserializeAsync(stream, Json, ct).ConfigureAwait(false); + } + catch (JsonException) { return null; } + catch (IOException) { return null; } + } + + private static DateTime Min(DateTime left, DateTime right) => left <= right ? left : right; + + public async Task ClearExceptAsync(IReadOnlySet enabledCameraIds, CancellationToken ct = default) + { + if (!Directory.Exists(_root)) return; + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + foreach (var directory in Directory.EnumerateDirectories(_root)) + { + ct.ThrowIfCancellationRequested(); + if (Guid.TryParseExact(Path.GetFileName(directory), "N", out var cameraId) && + enabledCameraIds.Contains(cameraId)) continue; + try { Directory.Delete(directory, recursive: true); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + finally { _gate.Release(); } + } + + public sealed record RecordingTriggerStatus(DateTime? FirstTriggeredAtUtc, DateTime? ActiveUntilUtc) + { + public static RecordingTriggerStatus Inactive { get; } = new(null, null); + public bool IsActive => ActiveUntilUtc is { } activeUntil && activeUntil > DateTime.UtcNow; + } + + private sealed record RecordingTrigger(DateTime OccurredAtUtc, DateTime ExpiresAtUtc); + + public void Dispose() => _gate.Dispose(); +} diff --git a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs index 30f1abc..467bb11 100644 --- a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs @@ -53,5 +53,5 @@ public class CreateCameraCommandHandler : IRequestHandler>; + bool? RecordingEnabled = null, + bool? EventRecordingEnabled = null) : IRequest>; public class UpdateCameraCommandHandler : IRequestHandler> { @@ -50,6 +51,7 @@ public class UpdateCameraCommandHandler : IRequestHandlerCamera response including all discovery and stream test metadata. public record CameraResponse( @@ -47,4 +48,5 @@ public record CameraResponse( bool HasAudio, bool HasMotionDetection, DateTime CreatedAt, - bool RecordingEnabled = false); + bool RecordingEnabled = false, + bool EventRecordingEnabled = false); diff --git a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs index 32d698e..8a6c59f 100644 --- a/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs +++ b/src/Heimdall.Application/Events/Commands/CreateEvent/CreateEventHandler.cs @@ -62,6 +62,17 @@ public class CreateEventHandler : IRequestHandler recording.CameraId == request.CameraId && + occurredAt >= recording.Timestamp && + occurredAt < recording.Timestamp.AddSeconds(recording.DurationSeconds)) + .OrderBy(recording => recording.Timestamp) + .Select(recording => (Guid?)recording.Id) + .FirstOrDefaultAsync(ct) + .ConfigureAwait(false); + if (matchingRecordingId.HasValue) + ev.AssignRecording(matchingRecordingId.Value); + _context.CameraEvents.Add(ev); try { diff --git a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs index 92f12bd..2c072da 100644 --- a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs +++ b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs @@ -45,7 +45,7 @@ public class GetCamerasByGroupHandler : IRequestHandler>.Success( diff --git a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs index d6a95c8..bafb172 100644 --- a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs +++ b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs @@ -33,9 +33,9 @@ public sealed class UploadRecordingHandler( var camera = await db.Cameras.AsNoTracking() .Where(c => c.Id == request.CameraId && !c.IsDeleted) - .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled }) + .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled, c.EventRecordingEnabled }) .SingleOrDefaultAsync(ct).ConfigureAwait(false); - if (camera?.AgentId != request.AgentId || !camera.RecordingEnabled) + if (camera?.AgentId != request.AgentId || !(camera.RecordingEnabled || camera.EventRecordingEnabled)) return ServiceResult.NotFound("Camera not found"); var existing = await db.Recordings.AsNoTracking() diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index 5b97fd2..2e847b7 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -122,6 +122,7 @@ public class GetEffectiveAgentConfigQueryHandler config[$"{prefix}.sub_rtsp"] = camera.SubRtspUrl; config[$"{prefix}.enabled"] = camera.Status != CameraStatus.Disabled ? "true" : "false"; config[$"{prefix}.recording_enabled"] = camera.RecordingEnabled ? "true" : "false"; + config[$"{prefix}.event_recording_enabled"] = camera.EventRecordingEnabled ? "true" : "false"; } return ServiceResult>.Success(config); diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs index fac65dd..63ff4b5 100644 --- a/src/Heimdall.Domain/Entities/Camera.cs +++ b/src/Heimdall.Domain/Entities/Camera.cs @@ -15,6 +15,8 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable public CameraStatus Status { get; private set; } = CameraStatus.Disabled; /// Whether the assigned Agent stores bounded video segments for this camera. public bool RecordingEnabled { get; private set; } + /// Whether detection events trigger short video captures while this camera is assigned. + public bool EventRecordingEnabled { get; private set; } // ── Discovery ─────────────────────────────────────────────────── /// How this camera was discovered (manual, ONVIF, mDNS, etc.). @@ -114,6 +116,7 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable public void SetStatus(CameraStatus status) => Status = status; public void SetRecordingEnabled(bool enabled) => RecordingEnabled = enabled; + public void SetEventRecordingEnabled(bool enabled) => EventRecordingEnabled = enabled; public void SetCapabilities(bool ptz, bool audio, bool motion) { diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs index 9648181..465b033 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs @@ -39,6 +39,10 @@ public class CameraConfiguration : IEntityTypeConfiguration .HasDefaultValue(false) .IsRequired(); + builder.Property(c => c.EventRecordingEnabled) + .HasDefaultValue(false) + .IsRequired(); + // ── Discovery ─────────────────────────────────────────────── builder.Property(c => c.DiscoveryMethod) .HasConversion() diff --git a/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.Designer.cs new file mode 100644 index 0000000..b71b8fb --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.Designer.cs @@ -0,0 +1,2897 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261105162836_AddEventTriggeredCameraRecording")] + partial class AddEventTriggeredCameraRecording + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuLoadPercent") + .HasColumnType("double precision"); + + b.Property("GpuName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + b.Property("LastAppliedCameraConfigAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedCameraConfigVersion") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("VramMb") + .HasColumnType("bigint"); + + b.Property("VramUsageBytes") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CapturedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuTemperatureCelsius") + .HasColumnType("double precision"); + + b.Property("GpuUtilizationPercent") + .HasColumnType("double precision"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CapturedAtUtc"); + + b.HasIndex("AgentId", "CapturedAtUtc") + .IsUnique(); + + b.HasIndex("SiteId", "CapturedAtUtc"); + + b.ToTable("agent_metric_samples", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssignedAgentId") + .HasColumnType("uuid"); + + b.Property("AttemptId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DispatchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("JobType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MaxExecutionTime") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(3000000000L); + + b.Property("MaxRetries") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(3); + + b.Property("ParametersJson") + .HasColumnType("jsonb"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("RequiredCpuCores") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("RequiredMemoryMb") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L); + + b.Property("RequiresGpu") + .HasColumnType("boolean"); + + b.Property("ResultJson") + .HasColumnType("jsonb"); + + b.Property("RetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId") + .HasDatabaseName("ix_analysis_jobs_camera"); + + b.HasIndex("AssignedAgentId", "Status") + .HasDatabaseName("ix_analysis_jobs_agent_workload") + .HasFilter("\"AssignedAgentId\" IS NOT NULL"); + + b.HasIndex("Status", "DispatchedAt") + .HasDatabaseName("ix_analysis_jobs_timeout"); + + b.HasIndex("Status", "Priority", "CreatedAt") + .HasDatabaseName("ix_analysis_jobs_pending"); + + b.ToTable("analysis_jobs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("EventRecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.HasIndex("StoragePolicyId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("ExecutionProfileJson") + .HasColumnType("text"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitCategory") + .HasColumnType("integer"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitIsPaired") + .HasColumnType("boolean"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitPort") + .HasColumnType("integer"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("SnapshotStorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageProvider") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SnapshotStorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id", "OccurredAt"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("MetadataJson"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("MetadataJson"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("MetadataJson"), new[] { "jsonb_path_ops" }); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.HasIndex("PersonId", "OccurredAt"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Consumed") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Verifying") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserId"); + + b.ToTable("login_challenges", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FailureReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("CameraId", "CreatedAt"); + + b.ToTable("manual_snapshot_requests", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeliveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastErrorType") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("LeaseExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NotificationId") + .HasColumnType("uuid"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)"); + + b.Property("ServiceUrl") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("NotificationId", "Channel") + .IsUnique() + .HasDatabaseName("ux_notification_deliveries_notification_channel"); + + b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt") + .HasDatabaseName("ix_notification_deliveries_dispatch"); + + b.ToTable("notification_deliveries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("StorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StorageLocationCaptured") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("AutoUpdateEnabled") + .HasColumnType("boolean"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FirstSeenAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LocalRoot") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("S3Bucket") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("character varying(256)"); + + b.Property("S3Endpoint") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("Provider") + .HasDatabaseName("ix_storage_destinations_provider"); + + b.ToTable("storage_destinations", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("UserId"); + + b.ToTable("user_cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId", "SiteId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.ToTable("UserCameraAccesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", null) + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "AssignedAgent") + .WithMany() + .HasForeignKey("AssignedAgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedAgent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.HasOne("Heimdall.Domain.Entities.Notification", null) + .WithMany() + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("GroupCameraAccesses"); + + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.cs b/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.cs new file mode 100644 index 0000000..19c87f9 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261105162836_AddEventTriggeredCameraRecording.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddEventTriggeredCameraRecording : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "EventRecordingEnabled", + table: "cameras", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "EventRecordingEnabled", + table: "cameras"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 86407ed..55fbfe5 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -659,6 +659,11 @@ namespace Heimdall.Infrastructure.Migrations .IsUnicode(false) .HasColumnType("character varying(20)"); + b.Property("EventRecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + b.Property("HasAudio") .HasColumnType("boolean"); diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index dc78268..ff259ae 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -115,6 +115,9 @@ else @Text["CameraDetail_RecordingHelp"] + + @Text["CameraDetail_EventRecordingHelp"] @@ -318,6 +321,7 @@ else private string _editName = ""; private string? _editRtspUrl; private bool _recordingEnabled; + private bool _eventRecordingEnabled; private string _editError = ""; private string _editSuccess = ""; private bool _loading = true; @@ -365,6 +369,7 @@ else _editName = _camera.Name; _editRtspUrl = _camera.RtspUrl; _recordingEnabled = _camera.RecordingEnabled; + _eventRecordingEnabled = _camera.EventRecordingEnabled; } } catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); } @@ -592,11 +597,13 @@ else _editSuccess = ""; try { - if (await Api.UpdateCameraAsync(Id, _editName, _editRtspUrl, null, recordingEnabled: _recordingEnabled)) + if (await Api.UpdateCameraAsync(Id, _editName, _editRtspUrl, null, + recordingEnabled: _recordingEnabled, eventRecordingEnabled: _eventRecordingEnabled)) { _editSuccess = Text["CameraDetail_Updated"]; if (_camera is not null) _camera.Name = _editName; if (_camera is not null) _camera.RecordingEnabled = _recordingEnabled; + if (_camera is not null) _camera.EventRecordingEnabled = _eventRecordingEnabled; } else _editError = Text["CameraDetail_UpdateError"]; } diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index 6dc3bed..dce3268 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -163,7 +163,8 @@ public class CamerasController : ControllerBase { if (!this.TryGetUserId(out var actorId)) return Unauthorized(); var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, - request.Manufacturer, request.Model, request.DetectionProfile, actorId, request.RecordingEnabled); + request.Manufacturer, request.Model, request.DetectionProfile, actorId, request.RecordingEnabled, + request.EventRecordingEnabled); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 031681b..ec33ac9 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -2385,6 +2385,12 @@ Stores rolling MP4 segments in the configured storage. Disabling stops new segments; retention removes expired recordings. + + Capture video on detection events + + + Starts capture when a detection event arrives (no pre-roll) and records for 30 seconds after the latest event. The camera stream must already be active. + Name diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 3d5cad1..ec8e908 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -2385,6 +2385,12 @@ Stocke des segments MP4 dans l’emplacement configuré. La désactivation arrête les nouveaux segments ; la rétention supprime les enregistrements arrivés à échéance. + + Déclencher des segments vidéo sur événement + + + Démarre la capture au premier événement de détection (sans pré-enregistrement) et prolonge la vidéo de 30 secondes après le dernier événement. Le flux caméra doit déjà être actif. + Nom diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index e38b556..cd2ffe4 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -2385,6 +2385,12 @@ Stocke des segments MP4 dans l’emplacement configuré. La désactivation arrête les nouveaux segments ; la rétention supprime les enregistrements arrivés à échéance. + + Déclencher des segments vidéo sur événement + + + Démarre la capture au premier événement de détection (sans pré-enregistrement) et prolonge la vidéo de 30 secondes après le dernier événement. Le flux caméra doit déjà être actif. + Nom diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 042b153..0b65b7c 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -573,11 +573,12 @@ public class HeimdallApiClient : IDisposable } public async Task UpdateCameraAsync(Guid id, string name, string? rtspUrl, string? status, - string? manufacturer = null, string? model = null, bool? recordingEnabled = null) + string? manufacturer = null, string? model = null, bool? recordingEnabled = null, + bool? eventRecordingEnabled = null) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/cameras/{id}", - new { name, rtspUrl, status, manufacturer, model, recordingEnabled }, Json); + new { name, rtspUrl, status, manufacturer, model, recordingEnabled, eventRecordingEnabled }, Json); return response.IsSuccessStatusCode; } @@ -1097,6 +1098,7 @@ public class CameraItem public string Status { get; set; } = "Unknown"; public DateTime CreatedAt { get; set; } public bool RecordingEnabled { get; set; } + public bool EventRecordingEnabled { get; set; } } /// diff --git a/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs index 5f26edd..a8212bd 100644 --- a/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs +++ b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs @@ -65,6 +65,19 @@ public class CameraConfigStoreTests store.Cameras.ShouldHaveSingleItem().RecordingEnabled.ShouldBeTrue(); } + [Fact] + public void ApplyCameraSetting_EventRecordingIsOptInAndPropagates() + { + var store = new CameraConfigStore(); + var id = Guid.NewGuid(); + store.ApplyCameraSetting($"camera.{id}.name", "Door"); + store.Cameras.ShouldHaveSingleItem().EventRecordingEnabled.ShouldBeFalse(); + + store.ApplyCameraSetting($"camera.{id}.event_recording_enabled", "true"); + + store.Cameras.ShouldHaveSingleItem().EventRecordingEnabled.ShouldBeTrue(); + } + [Fact] public void ApplyCameraSetting_InvalidKey_Ignored() { diff --git a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs index 2b6ec51..1fa0b17 100644 --- a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs @@ -1,5 +1,6 @@ using System.Globalization; using Heimdall.Agent.Services; +using Heimdall.Domain.Entities; using Heimdall.Domain.Enums; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Logging; @@ -84,6 +85,41 @@ public class DetectionReporterServiceTests } } + [Fact] + public async Task ReportAsync_EnabledEventRecordingPersistsTriggerUntilAfterPostRoll() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-event-recording-{Guid.NewGuid():N}"); + try + { + var cameraId = Guid.NewGuid(); + var occurredAt = DateTime.UtcNow; + var options = Options.Create(new AgentOptions + { + StateDirectory = directory, + RecordingEventPostRollSeconds = 20 + }); + var cameras = new CameraConfigStore(); + cameras.SetLocalFallback([new AgentCameraConfig(cameraId, "Door", "rtsp://camera/stream", null, + true, EventRecordingEnabled: true)]); + var triggers = new RecordingTriggerStore(options); + using var reporter = new DetectionReporterService( + new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" }, + Substitute.For(), Substitute.For>(), + options, cameras, triggers); + + (await reporter.ReportAsync(cameraId, EventType.PersonDetected, 0.9, "person", occurredAt: occurredAt)) + .ShouldBeTrue(); + + var status = await triggers.GetStatusAsync(cameraId); + status.IsActive.ShouldBeTrue(); + status.FirstTriggeredAtUtc.ShouldBe(CameraEvent.NormalizeOccurredAt(occurredAt)); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + [Fact] public async Task ManualSnapshots_KeepRequestIds_WithoutCooldown() { diff --git a/tests/Heimdall.Agent.Tests/RecordingTriggerStoreTests.cs b/tests/Heimdall.Agent.Tests/RecordingTriggerStoreTests.cs new file mode 100644 index 0000000..6ed3ef0 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/RecordingTriggerStoreTests.cs @@ -0,0 +1,99 @@ +using System.Text.Json; +using Heimdall.Agent.Services; +using Heimdall.Domain.Entities; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Tests; + +public sealed class RecordingTriggerStoreTests +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + [Fact] + public async Task RegisterAsync_PersistsActiveTriggerAcrossStoreInstances() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-recording-trigger-{Guid.NewGuid():N}"); + try + { + var cameraId = Guid.NewGuid(); + var occurredAt = DateTime.UtcNow.AddMilliseconds(-100); + var options = Options.Create(new AgentOptions + { + StateDirectory = directory, + RecordingEventPostRollSeconds = 20 + }); + await new RecordingTriggerStore(options).RegisterAsync(cameraId, occurredAt); + + var status = await new RecordingTriggerStore(options).GetStatusAsync(cameraId); + + status.IsActive.ShouldBeTrue(); + status.FirstTriggeredAtUtc.ShouldBe(CameraEvent.NormalizeOccurredAt(occurredAt)); + status.ActiveUntilUtc.ShouldNotBeNull(); + status.ActiveUntilUtc!.Value.ShouldBeInRange(DateTime.UtcNow.AddSeconds(18), DateTime.UtcNow.AddSeconds(21)); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public async Task GetStatusAsync_RemovesExpiredTrigger() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-recording-trigger-{Guid.NewGuid():N}"); + var cameraId = Guid.NewGuid(); + var cameraDirectory = Path.Combine(directory, "recording-triggers", cameraId.ToString("N")); + Directory.CreateDirectory(cameraDirectory); + var marker = Path.Combine(cameraDirectory, "trigger.json"); + try + { + await File.WriteAllTextAsync(marker, JsonSerializer.Serialize(new + { + occurredAtUtc = DateTime.UtcNow.AddMinutes(-1), + expiresAtUtc = DateTime.UtcNow.AddSeconds(-1) + }, Json)); + var store = new RecordingTriggerStore(Options.Create(new AgentOptions { StateDirectory = directory })); + + var status = await store.GetStatusAsync(cameraId); + + status.IsActive.ShouldBeFalse(); + File.Exists(marker).ShouldBeFalse(); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public async Task RegisterAsync_RefreshesOneBoundedMarkerPerCamera() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-recording-trigger-{Guid.NewGuid():N}"); + try + { + var cameraId = Guid.NewGuid(); + var options = Options.Create(new AgentOptions + { + StateDirectory = directory, + RecordingEventPostRollSeconds = 20 + }); + var store = new RecordingTriggerStore(options); + var firstOccurredAt = DateTime.UtcNow.AddSeconds(-2); + await store.RegisterAsync(cameraId, firstOccurredAt); + await store.RegisterAsync(cameraId, DateTime.UtcNow); + + var cameraDirectory = Path.Combine(directory, "recording-triggers", cameraId.ToString("N")); + Directory.GetFiles(cameraDirectory, "*.json").Length.ShouldBe(1); + var status = await store.GetStatusAsync(cameraId); + + status.IsActive.ShouldBeTrue(); + status.FirstTriggeredAtUtc.ShouldBe(CameraEvent.NormalizeOccurredAt(firstOccurredAt)); + status.ActiveUntilUtc.ShouldNotBeNull(); + status.ActiveUntilUtc!.Value.ShouldBeInRange(DateTime.UtcNow.AddSeconds(18), DateTime.UtcNow.AddSeconds(21)); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs index d1e0096..086ff08 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Cameras/UpdateCameraHandlerTests.cs @@ -69,6 +69,21 @@ public class UpdateCameraHandlerTests await context.Received(1).SaveChangesWithRetryAsync(ct: Arg.Any()); } + [Fact] + public async Task Update_camera_should_persist_event_recording_opt_in() + { + var context = Substitute.For(); + context.Cameras.Returns(MockDbSetHelper.CreateFor([_existingCamera])); + + var result = await new UpdateCameraCommandHandler(context).Handle( + new UpdateCameraCommand(_existingCamera.Id, _existingCamera.Name, _existingCamera.RtspUrl, null, + EventRecordingEnabled: true), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.EventRecordingEnabled.ShouldBeTrue(); + _existingCamera.EventRecordingEnabled.ShouldBeTrue(); + } + [Fact] public async Task Update_camera_should_record_actor_and_safe_old_new_values() { diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs index 8cff26b..71d3b30 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs @@ -68,6 +68,7 @@ public class GetEffectiveAgentConfigHandlerTests camera.AssignAgent(agent.Id); camera.SetStatus(CameraStatus.Online); camera.SetRecordingEnabled(true); + camera.SetEventRecordingEnabled(true); var context = CreateContext(agents: [agent], sites: [site], cameras: [camera]); var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector); @@ -75,6 +76,7 @@ public class GetEffectiveAgentConfigHandlerTests result.IsSuccess.ShouldBeTrue(); result.Data![ $"camera.{camera.Id}.recording_enabled"].ShouldBe("true"); + result.Data[$"camera.{camera.Id}.event_recording_enabled"].ShouldBe("true"); } [Fact] diff --git a/tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs b/tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs index 075cccd..e6cb10b 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/RecordingEventAssociationTests.cs @@ -119,16 +119,30 @@ public sealed class RecordingEventAssociationTests(PostgreSqlContainerFixture po content); upload.StatusCode.ShouldBe(HttpStatusCode.OK); + var lateEventId = Guid.NewGuid(); + var reportedAfterUpload = await agentClient.PostAsJsonAsync("api/events", new + { + cameraId, + type = (int)EventType.PersonDetected, + confidence = 0.9, + label = "late-inside", + metadataJson = (string?)null, + occurredAt = start.AddMilliseconds(750), + eventId = lateEventId + }); + reportedAfterUpload.StatusCode.ShouldBe(HttpStatusCode.OK); + await using var scope = factory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); var linkedEvents = await db.CameraEvents.AsNoTracking() - .Where(cameraEvent => eventIds.Values.Contains(cameraEvent.Id)) + .Where(cameraEvent => eventIds.Values.Contains(cameraEvent.Id) || cameraEvent.Id == lateEventId) .ToDictionaryAsync(cameraEvent => cameraEvent.Label!, cameraEvent => cameraEvent.RecordingId); linkedEvents["before"].ShouldBeNull(); linkedEvents["at-start"].ShouldBe(recordingId); linkedEvents["inside"].ShouldBe(recordingId); linkedEvents["at-end"].ShouldBeNull(); linkedEvents["after"].ShouldBeNull(); + linkedEvents["late-inside"].ShouldBe(recordingId); storage.ObjectCount.ShouldBe(1); } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs index f80b6d3..f2cae1e 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -63,6 +63,7 @@ public class CameraDetailTests : PageTestBase cut.Markup.ShouldContain("Hikvision"); cut.Markup.ShouldContain("DS-2CD"); cut.Markup.ShouldContain("En ligne"); + cut.Markup.ShouldContain("Déclencher des segments vidéo sur événement"); }); } diff --git a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientCoverageTests.cs b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientCoverageTests.cs index 71858ca..c8ca1d8 100644 --- a/tests/Heimdall.Web.Tests/Services/HeimdallApiClientCoverageTests.cs +++ b/tests/Heimdall.Web.Tests/Services/HeimdallApiClientCoverageTests.cs @@ -311,17 +311,18 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable } [Fact] - public async Task UpdateCameraAsync_SendsRecordingEnabledOptIn() + public async Task UpdateCameraAsync_SendsRecordingOptIns() { SetAuthToken(); _handler.QueueResponse(HttpStatusCode.OK); var result = await _sut.UpdateCameraAsync(Guid.NewGuid(), "Cam", "rtsp://cam", null, - recordingEnabled: true); + recordingEnabled: true, eventRecordingEnabled: true); Assert.True(result); using var body = System.Text.Json.JsonDocument.Parse(await _handler.LastRequest!.Content!.ReadAsStringAsync()); Assert.True(body.RootElement.GetProperty("recordingEnabled").GetBoolean()); + Assert.True(body.RootElement.GetProperty("eventRecordingEnabled").GetBoolean()); } [Fact] diff --git a/todo.md b/todo.md index 1cf9a06..e0d4141 100644 --- a/todo.md +++ b/todo.md @@ -48,7 +48,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Le 5 novembre, `RecordingEventAssociationTests.SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange` passe 1/1 dans le projet Compose jetable `hmd-recording-event-1793895250-6481` contre PostgreSQL : timestamps avant, au début, dans le segment, à la fin et après; seules les deux occurrences dans `[début, fin)` sont associées. Teardown vérifié 0 conteneur/volume/réseau et aucun tag d’image local; images SDK/PostgreSQL upstream conservées. Restent capture déclenchée par événement et validations caméra/codecs réels; item non terminé. Skill : `skills/video-recording/SKILL.md`. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Le 5 novembre, `RecordingEventAssociationTests.SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange` passe 1/1 dans le projet Compose jetable `hmd-recording-event-1793895250-6481` contre PostgreSQL : timestamps avant, au début, dans le segment, à la fin et après; seules les deux occurrences dans `[début, fin)` sont associées. Teardown vérifié 0 conteneur/volume/réseau et aucun tag d’image local; images SDK/PostgreSQL upstream conservées. Le 5 novembre 2026, la capture événementielle est implémentée : opt-in `EventRecordingEnabled` séparé du continu dans CameraDetail/API et configuration Agent, déclenchement sur Motion/Person/Vehicle/UnknownPerson/Face/Plate, fenêtre post-roll configurable (5–300 s, défaut 30), marqueur atomique borné à un fichier par caméra, reprise après redémarrage, suppression à désactivation/caméra désactivée/désaffectation; événements arrivant avant ou après l’upload sont associés. Compose jetable source-build `hmd-event-e2e-1793899172-25617` (Central, PostgreSQL, Agent, MediaMTX, FFmpeg) : Agent inscrit par le vrai jeton site, flux RTSP synthétique animé H.264/AAC, MotionDetected=1, enregistrement continu désactivé, segment reçu=1 et événement lié=1; redémarrage Agent durant le post-roll puis second segment reçu=2; désactivation API puis stabilisation à 2 sans nouvel upload. Les seuils de mouvement synthétiques sont abaissés pour rendre l’événement déterministe; l’inférence d’objets et la caméra physique ne sont pas validées. Images construites depuis cette source avec restore .NET 10 locked : `heimdall:hmd-event-e2e-1793899172-25617-central` et `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, supprimées et vérifiées absentes; zéro conteneur/volume/réseau après teardown. `RecordingTriggerStoreTests` 3/3 via SDK Compose `hmd-trigger-unit-1793899683-6893`, aucun tag local, zéro ressource. `RecordingEventAssociationTests` PostgreSQL 1/1 vérifie bornes demi-ouvertes et événement créé après upload; avant modification ciblée, suites Agent/Application/Web 29/29, 14/14, 8/8. FEAT-02 reste ouvert pour validation avec caméras/codecs réels. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. Le 5 novembre 2026, `CleanupLicensePlatesJob` purge aussi après 30 jours les événements `LicensePlateDetected` et leurs snapshots : objets supprimés d’abord sur la destination persistée; événements à provenance absente/incomplète conservés avec warning. Tests SQLite 3/3 couvrent conservation des événements récents/non OCR, suppression des snapshots avant les lignes et maintien de la ligne en cas d’échec storage. Test PostgreSQL de traduction EF et suppression 1/1 dans la recette Compose `hmd-plate-retention-pg-1793885533-16210`; restore locked depuis le source, credentials générés, volumes dédiés, cleanup 0/0/0. La recette ne construit pas d’image Heimdall et conserve les bases Postgres/SDK partagées. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); validation externe de la durée de rétention et revue privacy. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. @@ -58,7 +58,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La PR #122 ajoute `heimdall.ai.queue.dropped` et `heimdall.agent.disk.usage.percent`; la PR #123 fournit des règles Prometheus d’exemple pour les rejets, le backlog persistant et le disque (seuil disque à adapter); la PR #124 ajoute les âges observés des jobs en attente/en cours, les jobs échoués et la disponibilité du monitoring Hangfire; la PR #125 ajoute l’état agrégé de l’outbox notifications et des alertes sur les livraisons en échec, en retard ou au bail expiré; la PR #126 ajoute le signal de snapshot Central valide reçu. La jauge de viewers suit maintenant les réservations de sessions WebRTC, les arrêts explicites et les expirations; validation simulée locale le 5 novembre : suite ciblée Agent santé/métriques 32/32 (health check modèle absent, caméra sans flux, saturation CPU, backlog snapshots/inférence et disque); scrape HTTP Compose du 5 novembre sur l’image Central OCR déjà buildée depuis cette branche (hmd-metrics-scrape-1793874584) a répondu 200, contenu exposition Prometheus et métriques ASP.NET Core présentes; DSN Sentry vide; projet supprimé et vérifié 0/0/0. Ce n’est pas un scrape Prometheus déployé et ne mesure pas l’évolution réelle des métriques. Restent scraping et mesure sur déploiement. - [x] Ajouter `.agents/skills/secure-env-secrets/SKILL.md` : procédures pour lire/écrire les secrets fournis par l'utilisateur dans l'environnement local, avec stockage persistant optionnel hors dépôt, permissions utilisateur uniquement et sans exposer la valeur. Le skill ne configure pas les secrets des workflows distants. - [ ] Vérifier readiness et alertes pour modèle absent, file pleine, backlog, disque, jobs bloqués, perte de configuration et échec de livraison. Le contrôle stockage est aligné sur le fournisseur actif dans les réglages DB de l’IHM, avec probe d’écriture locale, probe du bucket S3 sélectionné et timeout borné ; les health checks IA convertissent aussi leurs timeouts internes en état dégradé tout en propageant l’annulation appelante. La PR #109 ajoute les tests de `/readyz` sain/stockage mal configuré (sans fuite de configuration), de `/health/live` avec IA optionnelle absente et de diagnostics Agent lorsque le modèle ou le flux de capture manque ; le run PR #327 a passé 383 tests Agent, 150 tests d’intégration PostgreSQL, 35 E2E sans test ignoré, les builds/scans serveur/Agent et `CI policy`. La PR #111, mergée, ajoute les diagnostics de saturation CPU et garantit que cette saturation reste `Unhealthy` même quand la capture est également périmée ; le run PR #335 a passé les tests, scans serveur/Agent et `CI policy`. La PR #112, mergée après les runs #370, ajoute les profondeurs des files snapshots et inférence ainsi que les snapshots abandonnés. La PR #113, mergée, ajoute le taux d’occupation disque au diagnostic santé Agent sans définir de seuil de dégradation. La PR #122 exporte snapshots rejetés et occupation disque; la PR #123 ajoute des règles Prometheus d’exemple pour pertes, backlog persistant et disque; la PR #124 exporte les âges Hangfire observés et ajoute les alertes de jobs anciens/échoués et de monitoring indisponible; la PR #125 ajoute les métriques agrégées de l’outbox et les alertes de livraison; la PR #126 exporte la réception d’un snapshot Central et ajoute une alerte opt-in pour les Agents attendus sur un site. Validation simulée locale Agent le 5 novembre : health checks et métriques ciblés 32/32 couvrent modèle absent, flux caméra manquant, saturation, backlog et disque. Le test ciblé HealthControllerTests PostgreSQL est repassé 5/5 le 5 novembre; l’échec réseau/stockage réel reste non validé; scrape manuel Compose de /metrics Central du 5 novembre : HTTP 200, format Prometheus et métriques ASP.NET Core visibles; image source-buildée précédente, DSN Sentry vide, teardown 0/0/0. Restent le scrape Prometheus déployé et les pannes/seuils réels. Le parcours Compose du 4 novembre a révélé que BusyBox `wget --spider` envoyait HEAD sur `/healthz` (405) alors que GET répond 200; Dockerfile et Compose utilisent maintenant `wget -O /dev/null` pour émettre GET. Skill : `skills/server-healthchecks/SKILL.md`; recette Compose source intégrée à l’acceptation finale. -- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in et son câblage installateur, corrige les indications backup obsolètes sur mc, et impose aux skills un `EXIT` cleanup trap préservant le statut des tests, vérifiant les ressources du projet et supprimant/vérifiant chaque tag local exact, même après échec; les images upstream partagées restent intactes, aucun `--rmi all`/prune. Le 5 novembre 2026, les recettes Docker SDK/mock et les recettes source-build Central/Agent ont été auditées; les instructions ont été complétées pour les cas « aucun tag local » et tags locaux. L’audit a aussi rétrogradé les preuves historiques ne documentant pas le contrôle d’absence exact (WebRTC et bootstrap vision) et interdit explicitement de réutiliser un tag d’une autre recette. La validation statique `git diff --check` reste à exécuter pour cette mise à jour. Les acceptations antérieures MotionDetection et FEAT-02 indiquent la suppression/vérification des tags; onze anciens tags d’acceptance avaient également été retirés/vérifiés absents. Les preuves OCR Compose réutilisaient une image locale antérieure et ne remplacent pas un build/tag unique de la recette courante. La fermeture DOC-01 reste ouverte tant que les autres guides et validations externes sont à jour. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. +- [ ] Actualiser les guides après chaque changement d’infrastructure, routes/API et statut produit ; distinguer implémenté, validé, partiel et prévu. Cette passe documente le lecteur OCR local opt-in et son câblage installateur, corrige les indications backup obsolètes sur mc, et impose aux skills un `EXIT` cleanup trap préservant le statut des tests, vérifiant les ressources du projet et supprimant/vérifiant chaque tag local exact, même après échec; les images upstream partagées restent intactes, aucun `--rmi all`/prune. Le 5 novembre 2026, les recettes Docker SDK/mock et les recettes source-build Central/Agent ont été auditées; les instructions ont été complétées pour les cas « aucun tag local » et tags locaux. L’audit a aussi rétrogradé les preuves historiques ne documentant pas le contrôle d’absence exact (WebRTC et bootstrap vision) et interdit explicitement de réutiliser un tag d’une autre recette. Le 5 novembre 2026, `git diff --check` passe après la mise à jour documentaire. Les acceptations antérieures MotionDetection et FEAT-02 indiquent la suppression/vérification des tags; onze anciens tags d’acceptance avaient également été retirés/vérifiés absents. Les preuves OCR Compose réutilisaient une image locale antérieure et ne remplacent pas un build/tag unique de la recette courante. La fermeture DOC-01 reste ouverte tant que les autres guides et validations externes sont à jour. Voir `skills/deployment-guide-acceptance/SKILL.md` et `skills/compose-disposable-recipe/SKILL.md`. ## Corrections déjà livrées à préserver -- 2.54.1 From 95602dc9156ba47597f056ee5f457c782326a2d6 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 19:33:13 +0100 Subject: [PATCH 35/40] fix(agent): trigger event recordings before outbox --- skills/agent-runtime-acceptance/SKILL.md | 2 + skills/camera-toggle-acceptance/SKILL.md | 53 +++++++++++++++++++ skills/gpu-inference/SKILL.md | 2 + skills/video-recording/SKILL.md | 2 +- .../Services/DetectionReporterService.cs | 11 ++-- .../DetectionReporterServiceTests.cs | 33 ++++++++++++ todo.md | 6 +-- 7 files changed, 101 insertions(+), 8 deletions(-) create mode 100644 skills/camera-toggle-acceptance/SKILL.md diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index 51459ce..de5df73 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -26,6 +26,8 @@ For the focused Kestrel ACK acceptance, copy only the test project's source depe This SDK-only recipe does not build a local Heimdall image; keep the shared upstream SDK image. If the recipe is extended to build an app image, assign a project-unique tag and remove/verify that exact tag after teardown per `skills/compose-disposable-recipe/SKILL.md`. +For camera enable/disable timing, distinguish Central's requested state, the exact configuration digest acknowledged by the Agent, and actual FFmpeg process release. A status transition alone is not proof that capture stopped. Poll `/proc//comm` (or an equivalent exact process identity that cannot match the harness command); measure stop convergence separately from config ACK convergence. The synthetic-camera acceptance must cover initial OFF, ON, OFF, ON, restart while ON, then OFF and restart while OFF with the persisted Agent identity, asserting the newest digest after each update. Record the observed OFF latency and keep the item open if it exceeds the product's 2-second expectation. Every attempt uses a new project and exact source-built Central/Agent tags, records both before build, and removes/verifies them plus all project resources in its EXIT trap. + ## Acceptance boundary In-memory SignalR/HTTP fixtures and a local Agent container validate reconnect and runtime behavior without a physical camera. Mark real-camera stream stability, resource release on the deployed host, and LAN discovery as open until they pass on representative hardware and network equipment. diff --git a/skills/camera-toggle-acceptance/SKILL.md b/skills/camera-toggle-acceptance/SKILL.md new file mode 100644 index 0000000..e3bb8b0 --- /dev/null +++ b/skills/camera-toggle-acceptance/SKILL.md @@ -0,0 +1,53 @@ +--- +name: camera-toggle-acceptance +description: Validate that Central camera enable/disable changes stop and resume the real Agent FFmpeg capture process and persist across Agent restarts. +--- + +# Camera enable/disable lifecycle + +Read `AGENTS.md`, the Toggle caméra #59/#199 entry in `todo.md`, `skills/heimdall-dotnet/SKILL.md`, and `skills/compose-disposable-recipe/SKILL.md` before changing this flow. + +## Implementation path + +- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. +- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest. +- `GetEffectiveAgentConfigQuery` emits `camera..enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`. +- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera. +- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state. + +## Local verification + +Run the focused Agent lifecycle suites: + +```bash +dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --filter 'FullyQualifiedName~CameraStreamServiceTests|FullyQualifiedName~SnapshotPipelineServiceTests' --no-restore +``` + +These tests cover session idempotence, process termination, and synchronization without claiming a full Central/Agent workflow. + +## Central + Agent disposable acceptance + +- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images. +- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials. +- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent. +- Toggle ON and confirm an Agent `ffmpeg` pull process exists against the synthetic path. Toggle OFF and verify the API says Disabled, Agent reports no assigned stream via its active process count and the FFmpeg process disappears in under 2 seconds. Toggle ON and verify the process returns within 10 seconds. +- Restart the Agent while ON; verify it reuses its single existing identity and restarts capture within 10 seconds. Then toggle OFF, restart again, and verify the camera remains Disabled and no capture process returns. +- Use `docker top` only to count FFmpeg processes; never print its command lines because they contain the RTSP URL. Record elapsed durations and sanitized HTTP statuses only. +- Install an EXIT cleanup trap before the first build/start. Teardown only the named Compose project, verify zero containers/volumes/networks, remove each exact project-unique Central/Agent image tag and verify absent, then delete the temporary environment and scripts. Keep the original test status and fail if cleanup verification fails. + +This acceptance proves the source-built Central/Agent software lifecycle with a synthetic RTSP stream. It does not validate hardware codecs, physical cameras, LAN multicast, or deployed-host timing. + +## Observed simulator pitfalls + +- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines. +- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result. +- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above. +- Current disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but have not yet proved toggle timing or restart persistence. Treat #59/#199 as open until a corrected process measurement completes the whole cycle. + +## Latest source-built run + +The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding self-counting by the measurement shell. It confirmed the Disabled baseline at zero processes and progressed through ON, OFF, ON, then Agent restart while ON with capture restored. The next OFF returned Central state Disabled and effective Agent config `enabled=false`, with zero FFmpeg processes, but the latest config digest was not acknowledged inside the two-second OFF bound. Therefore the full OFF/ON/restart acceptance is still incomplete; do not mark #59/#199 complete. Investigate whether Agent ACK version is stale or the API config digest changes after toggle, while keeping the OFF process release measurement distinct from ACK convergence. + +## Sixth source-built run + +The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold. diff --git a/skills/gpu-inference/SKILL.md b/skills/gpu-inference/SKILL.md index 8dc9679..8a2af4c 100644 --- a/skills/gpu-inference/SKILL.md +++ b/skills/gpu-inference/SKILL.md @@ -29,3 +29,5 @@ Use this skill when changing ONNX Runtime packages, execution provider configura ## Current limitation The optional GPU image, signed manifest publication, installer selection, and Docker auto-update variant are implemented. On 5 November 2026, the post-fix GPU image built from this source with locked GPU restore. Rendered Compose confirmed CPU has no NVIDIA device requirement and the opt-in overlay selects the GPU image. A local disposable runtime check launched the GPU image without NVIDIA devices on an isolated network and tmpfs state: logs confirmed no GPU detection, fallback to `CPUExecutionProvider`, and YOLO model initialization; a synthetic HTTP Central mock accepted registration and heartbeat (200/204), and `/healthz` returned 200. The repository `RealOnnx_CpuModel_ProcessesFullHdImage` test passed 1/1 with `HeimdallOnnxRuntime=GPU`. The mock did not implement configuration/jobs, so no camera frame traversed the Agent/Central loop; a synthetic frame and persisted inference observation remain open. The exact acceptance image tag and container were removed and verified absent; tmpfs, mock listener, and temporary state were gone. The earlier disposable Central/PostgreSQL bootstrap also passed. Physical CUDA execution still requires NVIDIA hardware. + +Additional full-loop acceptance attempt, 5 November 2026: disposable Compose project `hmgpu-loop-929b670e` rendered with CUDA package selection, no NVIDIA reservation, and empty Sentry DSN. Central and the Agent GPU image were built from this checkout under `heimdall:hmgpu-loop-929b670e-central` and `heimdall-agent:hmgpu-loop-929b670e-gpu` (GPU image inspected at 3.56 GB). The Compose/Buildx client remained waiting after image export and before any service/container was created, so no Central bootstrap, Agent health, camera configuration, job, frame processing, or database observation was exercised. After stopping only that build handle, cleanup verified 0 containers/0 volumes/0 networks, both exact image tags absent, and the temporary directory absent. `docker buildx ls` and `docker ps` responded afterward; this does not establish successful runtime acceptance. Keep the frame-through-job-loop evidence open. An earlier duplicate-target attempt (`hmgpu-loop-e9377c0b`) was also cleaned with 0/0/0 and both exact image tags absent. diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md index a2231ea..58ebefd 100644 --- a/skills/video-recording/SKILL.md +++ b/skills/video-recording/SKILL.md @@ -20,7 +20,7 @@ Recording is opt-in per camera (`RecordingEnabled`, default false). Agent captur - For acceptance, install an EXIT cleanup trap before build/start, then build Central and Agent from this changed source with unique image tags in a disposable Compose project. Publish a synthetic RTSP stream containing H.264 video and AAC-compatible audio through MediaMTX; register and assign the Agent, enable recording, and prove a segment reaches Central through the live Agent RTSP loop. Verify ffprobe sees video and audio in a downloaded segment, scoped listing/range download, and unauthorized denial. Remove only that Compose project, confirm its containers/volumes/network are gone, and remove/verify every recipe-built local image tag. - For quota acceptance, set `RECORDING_STORAGE_QUOTA_MAX_BYTES` to a small positive value such as 32, build Central from source, and probe `/healthz` plus `/api/auth/bootstrap-status` to prove startup validation. Run the PostgreSQL API test with concurrent uploads to prove the 507 boundary, idempotent retry, unique keys, and cleanup of over-quota/duplicate objects. Tear down the named Compose project and verify zero containers, volumes, and networks. - Run `RecordingEventAssociationTests` against PostgreSQL: upload a segment and verify that only same-camera events in the half-open interval `[timestamp, timestamp + duration)` receive its recording ID; events at either outside boundary remain unlinked. This confirms relational translation and event/recording association without claiming event-triggered capture. -- Event recording is an independent opt-in from continuous recording. Central sends `event_recording_enabled` in the per-Agent camera configuration; the Agent persists one atomic marker per camera, refreshed through the configured post-roll (5–300 seconds, default 30). Motion, person, vehicle, unknown-person, face, and plate events can refresh that window. The Agent starts FFmpeg only while the camera stream is active and the marker remains live. Clear markers when event recording is disabled, the camera is disabled, or assignment is removed. The marker is bounded to one file per camera and survives Agent restart. +- Event recording is an independent opt-in from continuous recording. Central sends `event_recording_enabled` in the per-Agent camera configuration; the Agent persists one atomic marker per camera before attempting the HTTP event outbox write, so outbox capacity or delivery cannot suppress capture. Each qualifying event refreshes the configured post-roll (5–300 seconds, default 30). Motion, person, vehicle, unknown-person, face, and plate events can refresh that window. The Agent starts FFmpeg only while the camera stream is active and the marker remains live. Clear markers when event recording is disabled, the camera is disabled, or assignment is removed. The marker is bounded to one file per camera and survives Agent restart. - For event-triggered acceptance, enable only `EventRecordingEnabled` through CameraDetail/API, use an assigned Agent and active synthetic RTSP stream, and prove the Agent starts capture and uploads a segment. Verify event association for both event-first and recording-first arrival. Restart the Agent during an active window and prove capture resumes from the marker; disable the toggle and prove uploads stop after configuration settles. Keep real-camera codec and timing validation separate. - For each recording recipe, record project-unique tags for locally built Central, Agent, or helper images and remove/verify those exact tags after Compose teardown in the same EXIT trap, including on build/assertion failure. Retain shared PostgreSQL/MediaMTX base images, preserve test exit status, report cleanup failures, and never use `--rmi all` or `image prune`. Follow `skills/compose-disposable-recipe/SKILL.md`. - Do not reuse an app/helper tag built by a different acceptance recipe. Build this recipe's changed source under fresh project-unique tags; record `local image tags: none` only for genuinely upstream-only test containers. Every run note must list the exact local tags as absent, or explicitly state no local images were built. diff --git a/src/Heimdall.Agent/Services/DetectionReporterService.cs b/src/Heimdall.Agent/Services/DetectionReporterService.cs index f1406f9..45abb14 100644 --- a/src/Heimdall.Agent/Services/DetectionReporterService.cs +++ b/src/Heimdall.Agent/Services/DetectionReporterService.cs @@ -129,10 +129,9 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo cameraId, type, confidence, label, metadataJson, occurredAt ?? now, eventId ?? Guid.NewGuid()); try { - var queued = await EnqueueAsync(request, snapshotJpeg, ct).ConfigureAwait(false); - if (!queued) - return false; - + // Persist the capture request as soon as the qualifying event is observed. + // The durable HTTP outbox can reject a report (or the process can stop + // before the outbox transaction); recording must not depend on delivery. if (ShouldTriggerRecording(type) && _cameras?.Cameras.Any(camera => camera.CameraId == cameraId && camera.EventRecordingEnabled) == true && _recordingTriggers is not null) { @@ -148,6 +147,10 @@ public sealed class DetectionReporterService : BackgroundService, IDetectionRepo } } + var queued = await EnqueueAsync(request, snapshotJpeg, ct).ConfigureAwait(false); + if (!queued) + return false; + if (type != EventType.ManualSnapshot) _lastQueued[key] = now; try { _wake.Release(); } catch (SemaphoreFullException) { } diff --git a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs index 1fa0b17..30543ba 100644 --- a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs @@ -120,6 +120,39 @@ public class DetectionReporterServiceTests } } + [Fact] + public async Task ReportAsync_EnabledEventRecordingPersistsTriggerWhenOutboxRejectsPayload() + { + var directory = Path.Combine(Path.GetTempPath(), $"heimdall-event-recording-rejected-{Guid.NewGuid():N}"); + try + { + var cameraId = Guid.NewGuid(); + var options = Options.Create(new AgentOptions + { + StateDirectory = directory, + RecordingEventPostRollSeconds = 20 + }); + var cameras = new CameraConfigStore(); + cameras.SetLocalFallback([new AgentCameraConfig(cameraId, "Door", "rtsp://camera/stream", null, + true, EventRecordingEnabled: true)]); + var triggers = new RecordingTriggerStore(options); + using var reporter = new DetectionReporterService( + new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" }, + Substitute.For(), Substitute.For>(), + options, cameras, triggers); + + var queued = await reporter.ReportAsync(cameraId, EventType.PersonDetected, 0.9, "person", + metadataJson: new string('x', 2 * 1024 * 1024)); + + queued.ShouldBeFalse(); + (await triggers.GetStatusAsync(cameraId)).IsActive.ShouldBeTrue(); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + [Fact] public async Task ManualSnapshots_KeepRequestIds_WithoutCooldown() { diff --git a/todo.md b/todo.md index e0d4141..08bee9a 100644 --- a/todo.md +++ b/todo.md @@ -37,7 +37,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **AGENT-08** Le Central simulé par Kestrel sert une configuration une seule fois; l’Agent applique une fois son snapshot, envoie deux ACK avec le même digest après un HTTP 503, puis Central persiste exactement un ACK avec HTTP 204. Test ciblé 1/1 et suite Agent 399/399 réussis localement. La recette Compose isolée construite depuis les dépendances source avec SDK 10.0.100 a exécuté le test Kestrel : configuration GET une fois, ACK même digest après 503 puis 204, application snapshot une fois, résultat 1/1. Le projet `hmdack_8df77197` a été démonté; conteneurs, volumes, réseau et source temporaire vérifiés/supprimés à 0. La validation sur Agent/caméra réels et coupure réseau reste ouverte. - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Validation simulée locale ajoutée le 5 novembre 2026 : tests ciblés SnapshotPipelineServiceTests, CameraStreamServiceTests, FrameAnalyzerServiceTests, PipelineDegradationManagerTests et FrameAnalyzerDegradationTests passent 88/88; couvre démarrages/arrêts répétés, arrêt de flux et nettoyage, saturation/rejets, dégradation/récupération. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. - [ ] **AGENT-10** Validation simulée locale le 5 novembre 2026 : les tests Agent ciblés passent 88/88 sur cycles start/stop, arrêts/répétitions et nettoyage du pipeline; ils ne simulent pas une charge soutenue ni une contrainte mémoire/CPU/disque complète. Restent la charge/restart/arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. -- [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Tests simulés Agent du 5 novembre (88/88 au total) couvrent start/stop répétés et nettoyage des flux; ils ne prouvent pas les délais OFF/ON ni persistance après reboot. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. +- [ ] **Toggle caméra #59/#199** L’interface détail empêche les doubles clics pendant le POST; tests Agent du 5 novembre (88/88 au total) couvrent start/stop répétés et nettoyage. Acceptance Central+Agent source en Compose jetable avec MediaMTX/FFmpeg synthétique : bootstrap, assignation et ACK digest exact confirmés; Disabled initial=0, ON, OFF, ON et restart-ON ont fonctionné au 5e essai. Le 6e essai a séparé mesure processus et ACK : Central est passé Disabled et config Agent `enabled=false`; compteur exact FFmpeg est passé à 0 après expiration du seuil de 2 s (donc délai OFF non conforme/non démontré), bien que l’ACK initial corresponde exactement à la version Central. Aucun essai complet n’a validé le restart-OFF avec identité persistée et ACK exact. Les six projets ont été nettoyés à 0 conteneur/volume/réseau et leurs tags source uniques vérifiés absents; conserver l’item ouvert. - [x] **Accès caméra #141** Les PR #65/#88/#100 valident API, remplacement UI atomique, chargement paginé, protection du brouillon et révocation des grants excédentaires (>500). Validation complétée sur la branche de clôture : `ResourceAccessTests` vérifie l’union direct + groupe et la révocation live; `HttpIsolationTests` exerce le pipeline HTTP avec périmètres; un test bUnit `GroupsPage_GererAccesCamera_AfficheSiteEtAccordePuisRetireLaCamera` vérifie l’affichage site/caméra et les appels d’ajout/retrait depuis l’UI. Les tests couvrent les priorités d’accès dans l’interface et la révocation; aucune caméra physique n’est requise pour cette gestion des autorisations. Skill dédiée : `skills/camera-access-groups/SKILL.md`. - [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel. - [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. Les scripts utilisent `POSTGRES_PASSWORD_FILE` et le test PostgreSQL utilise `backup.sh`/`restore.sh`; le banc `test-backup-restore.sh` monte maintenant son PG éphémère en `tmpfs` pour éviter le volume anonyme implicite. Test local : 11/11 assertions (données/FK, objet local, clé Data Protection et mode 0600). Le 4 novembre 2026, une recette Compose jetable avec deux volumes PostgreSQL nommés a restauré une ligne synthétique d’un dump source dans le volume cible en 1,93 s; l’archive du volume protégé a restauré l’objet et la clé avec SHA-256 et permissions identiques. Conteneurs, volumes, réseau et fichiers temporaires du projet ont été supprimés et vérifiés. Cette mesure synthétique n’est pas un RTO de production. L’intervalle nominal configuré est quotidien (dump PG 02:00 UTC, volume protégé 02:15 UTC), soit jusqu’à environ 24 h de perte pour chaque flux sans garantir un point atomique commun. Le 5 novembre 2026, le projet `hmdbk_a466d0ce` a vérifié le dump S3 daté, `latest.sql.gz`, sa restauration avec retour de `after-backup` à `before-restore`, l’upload protégé et le miroir RustFS/manifest. La recette a aussi révélé que l’ancien téléchargement de `mc` échouait en HTTP 410 et que BusyBox `date` ne calculait pas les seuils relatifs; Compose installe maintenant AWS CLI, Bash et GNU coreutils, et chaque appel AWS reçoit les clés configurées. Une nouvelle acceptance depuis `docker/docker-compose.backup.yml` + overlay jetable a vérifié le roundtrip PostgreSQL `after-backup`→`before-restore`, la purge de clés journalières et hebdomadaires anciennes, le manifeste RustFS et l’upload protégé; teardown vérifié à 0 conteneur/volume/réseau. Les mesures RPO/RTO sur installation/données réelles restent externes. Le run PR #388 a passé tests/builds, scans serveur/Agent et `CI policy`; le runbook reste dans `docker/backup/README.md`. @@ -48,9 +48,9 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. -- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Le 5 novembre, `RecordingEventAssociationTests.SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange` passe 1/1 dans le projet Compose jetable `hmd-recording-event-1793895250-6481` contre PostgreSQL : timestamps avant, au début, dans le segment, à la fin et après; seules les deux occurrences dans `[début, fin)` sont associées. Teardown vérifié 0 conteneur/volume/réseau et aucun tag d’image local; images SDK/PostgreSQL upstream conservées. Le 5 novembre 2026, la capture événementielle est implémentée : opt-in `EventRecordingEnabled` séparé du continu dans CameraDetail/API et configuration Agent, déclenchement sur Motion/Person/Vehicle/UnknownPerson/Face/Plate, fenêtre post-roll configurable (5–300 s, défaut 30), marqueur atomique borné à un fichier par caméra, reprise après redémarrage, suppression à désactivation/caméra désactivée/désaffectation; événements arrivant avant ou après l’upload sont associés. Compose jetable source-build `hmd-event-e2e-1793899172-25617` (Central, PostgreSQL, Agent, MediaMTX, FFmpeg) : Agent inscrit par le vrai jeton site, flux RTSP synthétique animé H.264/AAC, MotionDetected=1, enregistrement continu désactivé, segment reçu=1 et événement lié=1; redémarrage Agent durant le post-roll puis second segment reçu=2; désactivation API puis stabilisation à 2 sans nouvel upload. Les seuils de mouvement synthétiques sont abaissés pour rendre l’événement déterministe; l’inférence d’objets et la caméra physique ne sont pas validées. Images construites depuis cette source avec restore .NET 10 locked : `heimdall:hmd-event-e2e-1793899172-25617-central` et `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, supprimées et vérifiées absentes; zéro conteneur/volume/réseau après teardown. `RecordingTriggerStoreTests` 3/3 via SDK Compose `hmd-trigger-unit-1793899683-6893`, aucun tag local, zéro ressource. `RecordingEventAssociationTests` PostgreSQL 1/1 vérifie bornes demi-ouvertes et événement créé après upload; avant modification ciblée, suites Agent/Application/Web 29/29, 14/14, 8/8. FEAT-02 reste ouvert pour validation avec caméras/codecs réels. Skill : `skills/video-recording/SKILL.md`. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Le 5 novembre, `RecordingEventAssociationTests.SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange` passe 1/1 dans le projet Compose jetable `hmd-recording-event-1793895250-6481` contre PostgreSQL : timestamps avant, au début, dans le segment, à la fin et après; seules les deux occurrences dans `[début, fin)` sont associées. Teardown vérifié 0 conteneur/volume/réseau et aucun tag d’image local; images SDK/PostgreSQL upstream conservées. Le 5 novembre 2026, la capture événementielle est implémentée : opt-in `EventRecordingEnabled` séparé du continu dans CameraDetail/API et configuration Agent, déclenchement sur Motion/Person/Vehicle/UnknownPerson/Face/Plate, fenêtre post-roll configurable (5–300 s, défaut 30), marqueur atomique borné à un fichier par caméra, reprise après redémarrage, suppression à désactivation/caméra désactivée/désaffectation; événements arrivant avant ou après l’upload sont associés. Compose jetable source-build `hmd-event-e2e-1793899172-25617` (Central, PostgreSQL, Agent, MediaMTX, FFmpeg) : Agent inscrit par le vrai jeton site, flux RTSP synthétique H.264/AAC, MotionDetected=1, enregistrement continu désactivé, segment reçu=1 et événement lié=1; redémarrage Agent durant le post-roll puis second segment reçu=2; désactivation API puis stabilisation à 2 sans nouvel upload. Les seuils de mouvement synthétiques sont abaissés pour rendre l’événement déterministe; l’inférence d’objets et la caméra physique ne sont pas validées. Images construites depuis cette source avec restore .NET 10 locked : `heimdall:hmd-event-e2e-1793899172-25617-central` et `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, supprimées et vérifiées absentes; zéro conteneur/volume/réseau après teardown. `RecordingTriggerStoreTests` 3/3 via SDK Compose `hmd-trigger-unit-1793899683-6893`, aucun tag local, zéro ressource. `RecordingEventAssociationTests` PostgreSQL 1/1 vérifie bornes demi-ouvertes et événement créé après upload; avant modification ciblée, suites Agent/Application/Web 29/29, 14/14, 8/8. Le 5 novembre, la suite Agent ciblée `RecordingTriggerStoreTests|DetectionReporterServiceTests` passe 19/19 depuis la source via SDK Compose `hmd-event-agent-test-1793903398-364902` après restore locked; elle couvre maintenant le trigger durable même si l’outbox rejette un payload trop volumineux. Aucun tag local créé; cleanup vérifié 0 conteneur/volume/réseau et sources temporaires supprimées. FEAT-02 reste ouvert pour validation avec caméras/codecs réels. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. Le 5 novembre 2026, `CleanupLicensePlatesJob` purge aussi après 30 jours les événements `LicensePlateDetected` et leurs snapshots : objets supprimés d’abord sur la destination persistée; événements à provenance absente/incomplète conservés avec warning. Tests SQLite 3/3 couvrent conservation des événements récents/non OCR, suppression des snapshots avant les lignes et maintien de la ligne en cas d’échec storage. Test PostgreSQL de traduction EF et suppression 1/1 dans la recette Compose `hmd-plate-retention-pg-1793885533-16210`; restore locked depuis le source, credentials générés, volumes dédiés, cleanup 0/0/0. La recette ne construit pas d’image Heimdall et conserve les bases Postgres/SDK partagées. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); validation externe de la durée de rétention et revue privacy. Détails : `skills/vision-identity/SKILL.md`. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Restent la frame synthétique traitée par la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Le 5 novembre, deux essais de boucle complète Compose (`hmgpu-loop-e9377c0b`, `hmgpu-loop-929b670e`) ont construit l’image Central et l’image GPU depuis ce checkout avec tags uniques; Buildx s’est toutefois bloqué après export et avant création des services, donc aucun frame/job/observation persisté n’a été validé. Les deux essais ont été démontés avec 0 conteneur/volume/réseau, tags exacts absents et répertoires temporaires retirés. Restent la frame synthétique traitée et l’observation persistée dans la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. Détails : `skills/gpu-inference/SKILL.md`. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Corrigé : une annonce SRV sans A pour son hôte ne peut plus emprunter l'adresse d'une annonce sans lien. Tests synthétiques DNS-SD PTR/SRV/TXT/A, mapping `HomeKitMdnsProbe` et intégration de `NetworkCameraScanner` ajoutés : ciblé 8/8, suite Agent 404/404. Acceptance Compose jetable construite depuis la copie source, SDK `10.0.100`, restore locked et tests ciblés 8/8 ; projet `heimdall-mdns-ed8cc62e0a` supprimé avec `down --volumes --remove-orphans`, vérification 0 conteneur/0 volume/0 réseau et copie temporaire supprimée. `git diff --check` repassé le 5 novembre après les changements documentaires. La recette valide le parsing/mapping synthétique, pas le multicast ; validation sur LAN avec caméra/sonnette réelles reste ouverte. - [x] **UI groupes #138 / accès #134** L’éditeur permet de parcourir les comptes par nom/e-mail, de lister et retirer les membres, et d’accorder/révoquer les accès caméra avec nom de caméra et site. Le 4 novembre 2026, la revue a trouvé puis corrigé le POST membre qui visait une route inexistante; le client utilise désormais `POST /api/groups/{groupId}/users/{userId}` et `GET /api/groups/{groupId}/users`. Vérifications : Web groupes + client API 39/39; matrice d’autorisation Web 14/14; CameraAccessService Infrastructure 25/25; scénario PostgreSQL relationnel 1/1 valide l’union direct/groupe, le maintien du droit restant après révocation de l’autre, puis l’arrêt du grant d’un groupe supprimé. Recette Compose source jetable : bootstrap Admin, création groupe, ajout/liste/retrait membre et liste vide, tous HTTP 200; conteneurs, volumes, réseau et secrets temporaires vérifiés supprimés. Skill : `skills/group-access/SKILL.md`. -- 2.54.1 From 848a050fadc6b4ed261981dd2d998bf2c73887b4 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 19:56:02 +0100 Subject: [PATCH 36/40] feat(live): relay optional audio over WebRTC --- skills/webrtc-live/SKILL.md | 18 +++- .../Services/LiveCameraRelayService.cs | 17 +-- src/Heimdall.Web/wwwroot/js/live-view.js | 4 + .../LiveCameraRelayServiceTests.cs | 26 +++++ .../Heimdall.E2E.Tests/Pages/LiveViewTests.cs | 100 ++++++++++++++++++ todo.md | 2 +- 6 files changed, 155 insertions(+), 12 deletions(-) create mode 100644 tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md index 0ffc9c6..746c07d 100644 --- a/skills/webrtc-live/SKILL.md +++ b/skills/webrtc-live/SKILL.md @@ -11,9 +11,11 @@ and external network behavior is measured. present in the current Central assignment snapshot may be published. Stop the publisher when assignment, enablement, configuration, or Agent lifetime ends. - Use MediaMTX as the WebRTC/WHEP media server. Agent publishes the camera's - browser-compatible H.264 stream to a camera-ID path. Prefer passthrough when - the source codec is compatible; otherwise make transcoding an explicit, - bounded option. Start video-only; audio and PTZ require separate acceptance. + browser-compatible H.264 stream to a camera-ID path. The relay passes video + through and optionally maps the first audio track, transcoding it to Opus for + WebRTC browser compatibility; a source without audio must still publish. + Prefer passthrough when the source video codec is compatible; otherwise make + video transcoding an explicit, bounded option. PTZ remains separate. - Central issues random, short-lived, purpose-separated publish and read claims scoped to one camera and one action. Protect claims with the shared Heimdall Data Protection key ring. MediaMTX HTTP auth must validate exact path, action, @@ -59,7 +61,9 @@ the Agent. Configure its assigned camera against the host loopback RTSP port. Do 1. An assigned Agent receives only its assigned camera's short-lived publish credential and publishes synthetic H.264 to that camera path. 2. An authorized user obtains a short-lived read claim and a browser-compatible - WHEP session; the browser receives decoded frames. + WHEP session; the browser receives decoded frames. With synthetic audio, + prove the browser negotiates audio and video; playback starts muted for + autoplay compatibility and the native controls allow the viewer to enable it. 3. An unassigned Agent, cross-camera claim, wrong action/path/protocol, expired token, and user without camera access are rejected. 4. Disable/reassign camera, stop Agent, end viewer, and expire claim; verify the @@ -80,4 +84,8 @@ the upstream MediaMTX and FFmpeg images, which remain installed. The cleanup record is complete only after both local tags have been removed and an exact-tag `docker image inspect` confirms absence. -Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and the Agent relay test (1/1) pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Its historical record lacks exact-tag image absence checks, so repeat this recipe under the cleanup requirements above before treating cleanup as fully verified. Physical camera, LAN and external TURN are unvalidated; audio/PTZ remain out of scope, so keep FEAT-01 open. +Record LAN browser and external TURN runs independently. Focused API/Web ticket/session tests (7/7) and Agent relay tests pass. On 5 November 2026, disposable project `hmd-wrtc-75d1f49f` was built from this source with a synthetic H.264 RTSP source. Central bootstrap/site creation, Agent registration and camera assignment passed. Headless Chromium ran the actual `live-view.js` WHEP path and decoded a 640×360 frame (one video track); WHEP resource deletion returned 200 and Central session release 204. The MediaMTX auth callback accepted the valid read ticket and rejected altered action/path/protocol and a forged ticket (401); unknown camera access was denied. The API disable action stopped the scoped Agent publisher process from one to zero. Log scans found no admin/session/site credentials or RTSP source URL. The run exposed and fixed MediaMTX env interpolation and Docker ICE port mapping in the local recipe. The project was torn down with `down --volumes --remove-orphans`; project-scoped checks found zero containers, volumes and networks, and temporary secrets were deleted. Its historical record lacks exact-tag image absence checks, so repeat this recipe under the cleanup requirements above before treating cleanup as fully verified. Physical camera, LAN, external TURN and PTZ remain unvalidated. Synthetic audio codec and browser-track acceptance is recorded separately below; keep FEAT-01 open for its remaining external items. + +## Synthetic audio acceptance + +Run a disposable Compose source build plus a synthetic H.264+sine RTSP publisher. The source-built Agent tests must assert the relay command maps `0:a:0?`, converts audio to Opus, and does not disable audio. The Compose stream must be pulled from the relay and inspected to confirm H.264 video and Opus audio. Also run the authenticated WHEP browser flow and assert its media stream contains both tracks; no physical camera or external TURN claim follows from this recipe. Build app images with unique tags and remove/verify those exact tags in the same EXIT cleanup trap, or explicitly record `local image tags: none` for SDK/upstream-only test runs. diff --git a/src/Heimdall.Agent/Services/LiveCameraRelayService.cs b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs index f0b31ec..caaa120 100644 --- a/src/Heimdall.Agent/Services/LiveCameraRelayService.cs +++ b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs @@ -72,12 +72,7 @@ public sealed class LiveCameraRelayService( var session = await response.Content.ReadFromJsonAsync(cancellationToken: ct); if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false; - var source = camera.RtspUrl; - var start = new ProcessStartInfo { FileName = "ffmpeg", UseShellExecute = false, - RedirectStandardError = true, RedirectStandardOutput = false, CreateNoWindow = true }; - foreach (var arg in new[] { "-nostdin", "-hide_banner", "-loglevel", "error", "-fflags", "nobuffer", "-flags", "low_delay", "-rtsp_transport", "tcp", "-i", source, - "-map", "0:v:0", "-an", "-c:v", "copy", "-f", "rtsp", "-rtsp_transport", "tcp", destination.ToString() }) - start.ArgumentList.Add(arg); + var start = CreateStartInfo("ffmpeg", camera.RtspUrl, destination); try { var process = Process.Start(start); @@ -90,6 +85,16 @@ public sealed class LiveCameraRelayService( catch (Exception ex) { logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; } } + internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string source, Uri destination) + { + var start = new ProcessStartInfo { FileName = ffmpegPath, UseShellExecute = false, + RedirectStandardError = true, RedirectStandardOutput = false, CreateNoWindow = true }; + foreach (var arg in new[] { "-nostdin", "-hide_banner", "-loglevel", "error", "-fflags", "nobuffer", "-flags", "low_delay", "-rtsp_transport", "tcp", "-i", source, + "-map", "0:v:0", "-map", "0:a:0?", "-c:v", "copy", "-c:a", "libopus", "-b:a", "64k", "-f", "rtsp", "-rtsp_transport", "tcp", destination.ToString() }) + start.ArgumentList.Add(arg); + return start; + } + private static async Task DrainErrorsAsync(Process process) { try { while (await process.StandardError.ReadLineAsync() is not null) { } } diff --git a/src/Heimdall.Web/wwwroot/js/live-view.js b/src/Heimdall.Web/wwwroot/js/live-view.js index b274b26..5702fee 100644 --- a/src/Heimdall.Web/wwwroot/js/live-view.js +++ b/src/Heimdall.Web/wwwroot/js/live-view.js @@ -17,8 +17,12 @@ export async function start(cameraId, video) { const state = { pc, token: s.token, url: s.url, sessionId: s.sessionId, resource: null }; active.set(cameraId, state); pc.addTransceiver("video", { direction: "recvonly" }); + pc.addTransceiver("audio", { direction: "recvonly" }); pc.ontrack = e => { video.srcObject = e.streams[0]; + // Start muted so browsers permit autoplay; the native video controls let + // the viewer explicitly enable audio after playback starts. + video.muted = true; video.play().catch(() => {}); e.track.addEventListener("ended", () => void stop(cameraId), { once: true }); }; diff --git a/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs index 1086cd9..277ce00 100644 --- a/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs @@ -4,6 +4,24 @@ namespace Heimdall.Agent.Tests; public sealed class LiveCameraRelayServiceTests { + [Fact] + public void Publisher_PassesThroughVideoAndTranscodesOptionalAudioToWebRtcCompatibleOpus() + { + var source = new Uri("rtsp://camera.invalid/stream"); + var destination = new Uri("rtsps://media.invalid/camera?token=opaque"); + + var start = LiveCameraRelayService.CreateStartInfo("ffmpeg", source.ToString(), destination); + var args = start.ArgumentList.ToArray(); + + Assert.Equal("ffmpeg", start.FileName); + Assert.Equal("copy", OptionValue(args, "-c:v")); + Assert.Equal("0:a:0?", OptionValue(args, "-map", 1)); + Assert.Equal("libopus", OptionValue(args, "-c:a")); + Assert.Equal("64k", OptionValue(args, "-b:a")); + Assert.DoesNotContain("-an", args); + Assert.Equal(destination.ToString(), args[^1]); + } + [Fact] public void Uses_only_enabled_Rtsp_cameras_from_authoritative_Central_assignment_and_caps_publishers() { @@ -29,4 +47,12 @@ public sealed class LiveCameraRelayServiceTests Assert.DoesNotContain(fallback.CameraId, selected.Keys); Assert.DoesNotContain(invalidId, selected.Keys); } + + private static string OptionValue(string[] args, string option, int occurrence = 0) + { + var indices = args.Select((arg, index) => (arg, index)).Where(item => item.arg == option) + .Select(item => item.index).ToArray(); + Assert.True(indices.Length > occurrence, $"Missing {option} occurrence {occurrence}"); + return args[indices[occurrence] + 1]; + } } diff --git a/tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs b/tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs new file mode 100644 index 0000000..d264c88 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs @@ -0,0 +1,100 @@ +using System.Net; +using System.Text.Json; +using Shouldly; + +namespace Heimdall.E2E.Tests.Pages; + +[Collection("E2E")] +public sealed class LiveViewTests : E2ETestBase +{ + public LiveViewTests(TestCommon.PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay() + { + var cameraId = Guid.NewGuid(); + await Page.RouteAsync("**/api/live-media/**", async route => + { + var request = route.Request; + if (request.Url.EndsWith("/session", StringComparison.Ordinal)) + { + await route.FulfillAsync(new() + { + Status = (int)HttpStatusCode.OK, + ContentType = "application/json", + Body = JsonSerializer.Serialize(new + { + url = $"{BaseUrl}/media/{cameraId:D}/whep", + token = "synthetic-read-ticket", + sessionId = Guid.NewGuid(), + iceServers = Array.Empty() + }) + }); + return; + } + + await route.FulfillAsync(new() { Status = (int)HttpStatusCode.NoContent }); + }); + await Page.RouteAsync("**/media/**/whep", route => route.FulfillAsync(new() + { + Status = (int)HttpStatusCode.Created, + ContentType = "application/sdp", + Headers = new Dictionary { ["Location"] = "/media/session-resource" }, + Body = "v=0\r\n" + })); + await Page.RouteAsync("**/media/session-resource", route => route.FulfillAsync(new() + { + Status = (int)HttpStatusCode.NoContent + })); + + await Page.GotoAsync($"{BaseUrl}/login"); + await Page.EvaluateAsync(""" + () => { + window.__liveViewTransceivers = []; + window.__liveViewTracks = []; + window.RTCPeerConnection = class { + constructor() { this.iceGatheringState = 'complete'; } + addTransceiver(kind, options) { window.__liveViewTransceivers.push({ kind, direction: options.direction }); } + async createOffer() { return { type: 'offer', sdp: 'v=0\\r\\n' }; } + async setLocalDescription(description) { this.localDescription = description; } + async setRemoteDescription() { + const stream = new MediaStream(); + for (const kind of ['video', 'audio']) { + window.__liveViewTracks.push(kind); + this.ontrack({ streams: [stream], track: { kind, addEventListener() {} } }); + } + } + addEventListener() {} + close() {} + }; + } + """); + + var result = await Page.EvaluateAsync(""" + async cameraId => { + const video = document.createElement('video'); + video.dataset.liveCamera = cameraId; + video.play = async () => { window.__liveViewPlayCalled = true; }; + document.body.append(video); + const live = await import('/js/live-view.js'); + await live.start(cameraId, video); + const value = { + transceivers: window.__liveViewTransceivers, + tracks: window.__liveViewTracks, + muted: video.muted, + playCalled: window.__liveViewPlayCalled + }; + await live.stop(cameraId); + return value; + } + """, cameraId.ToString("D")); + + result.GetProperty("transceivers").EnumerateArray().Select(x => x.GetProperty("kind").GetString()) + .ShouldBe(new[] { "video", "audio" }); + result.GetProperty("transceivers").EnumerateArray().ShouldAllBe(x => + x.GetProperty("direction").GetString() == "recvonly"); + result.GetProperty("tracks").EnumerateArray().Select(x => x.GetString()).ShouldBe(new[] { "video", "audio" }); + result.GetProperty("muted").GetBoolean().ShouldBeTrue(); + result.GetProperty("playCalled").GetBoolean().ShouldBeTrue(); + } +} diff --git a/todo.md b/todo.md index 08bee9a..58aefbd 100644 --- a/todo.md +++ b/todo.md @@ -47,7 +47,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. -- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Caméra physique, LAN et TURN externe restent non testés; audio/PTZ, transcodage et budget de latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Le 5 novembre, le relais Agent passe aussi une piste audio source facultative en Opus : tests `LiveCameraRelayServiceTests` 2/2 sur source copiée et restore locked en SDK Compose, et recette MediaMTX/FFmpeg synthétique `hmd-webrtc-audio-1793903836-366262` confirme par ffprobe les flux `h264,video` et `opus,audio`. Aucun tag local créé; teardown vérifié zéro conteneur/volume/réseau, sources temporaires supprimées. L’UI réserve maintenant audio+vidéo en réception et démarre muette. `LiveViewTests.Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay` passe 1/1 sous Chromium avec un faux RTCPeerConnection qui injecte les deux pistes; compilation E2E source .NET 10 réussie sans avertissement. Cela vérifie la négociation et l’UI, pas le décodage du flux audio sur WHEP réel. Caméra physique, LAN et TURN externe, piste audio navigateur sur MediaMTX, PTZ, transcodage vidéo et budget latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Le 5 novembre, `RecordingEventAssociationTests.SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange` passe 1/1 dans le projet Compose jetable `hmd-recording-event-1793895250-6481` contre PostgreSQL : timestamps avant, au début, dans le segment, à la fin et après; seules les deux occurrences dans `[début, fin)` sont associées. Teardown vérifié 0 conteneur/volume/réseau et aucun tag d’image local; images SDK/PostgreSQL upstream conservées. Le 5 novembre 2026, la capture événementielle est implémentée : opt-in `EventRecordingEnabled` séparé du continu dans CameraDetail/API et configuration Agent, déclenchement sur Motion/Person/Vehicle/UnknownPerson/Face/Plate, fenêtre post-roll configurable (5–300 s, défaut 30), marqueur atomique borné à un fichier par caméra, reprise après redémarrage, suppression à désactivation/caméra désactivée/désaffectation; événements arrivant avant ou après l’upload sont associés. Compose jetable source-build `hmd-event-e2e-1793899172-25617` (Central, PostgreSQL, Agent, MediaMTX, FFmpeg) : Agent inscrit par le vrai jeton site, flux RTSP synthétique H.264/AAC, MotionDetected=1, enregistrement continu désactivé, segment reçu=1 et événement lié=1; redémarrage Agent durant le post-roll puis second segment reçu=2; désactivation API puis stabilisation à 2 sans nouvel upload. Les seuils de mouvement synthétiques sont abaissés pour rendre l’événement déterministe; l’inférence d’objets et la caméra physique ne sont pas validées. Images construites depuis cette source avec restore .NET 10 locked : `heimdall:hmd-event-e2e-1793899172-25617-central` et `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, supprimées et vérifiées absentes; zéro conteneur/volume/réseau après teardown. `RecordingTriggerStoreTests` 3/3 via SDK Compose `hmd-trigger-unit-1793899683-6893`, aucun tag local, zéro ressource. `RecordingEventAssociationTests` PostgreSQL 1/1 vérifie bornes demi-ouvertes et événement créé après upload; avant modification ciblée, suites Agent/Application/Web 29/29, 14/14, 8/8. Le 5 novembre, la suite Agent ciblée `RecordingTriggerStoreTests|DetectionReporterServiceTests` passe 19/19 depuis la source via SDK Compose `hmd-event-agent-test-1793903398-364902` après restore locked; elle couvre maintenant le trigger durable même si l’outbox rejette un payload trop volumineux. Aucun tag local créé; cleanup vérifié 0 conteneur/volume/réseau et sources temporaires supprimées. FEAT-02 reste ouvert pour validation avec caméras/codecs réels. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. Le 5 novembre 2026, `CleanupLicensePlatesJob` purge aussi après 30 jours les événements `LicensePlateDetected` et leurs snapshots : objets supprimés d’abord sur la destination persistée; événements à provenance absente/incomplète conservés avec warning. Tests SQLite 3/3 couvrent conservation des événements récents/non OCR, suppression des snapshots avant les lignes et maintien de la ligne en cas d’échec storage. Test PostgreSQL de traduction EF et suppression 1/1 dans la recette Compose `hmd-plate-retention-pg-1793885533-16210`; restore locked depuis le source, credentials générés, volumes dédiés, cleanup 0/0/0. La recette ne construit pas d’image Heimdall et conserve les bases Postgres/SDK partagées. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); validation externe de la durée de rétention et revue privacy. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Le 5 novembre, deux essais de boucle complète Compose (`hmgpu-loop-e9377c0b`, `hmgpu-loop-929b670e`) ont construit l’image Central et l’image GPU depuis ce checkout avec tags uniques; Buildx s’est toutefois bloqué après export et avant création des services, donc aucun frame/job/observation persisté n’a été validé. Les deux essais ont été démontés avec 0 conteneur/volume/réseau, tags exacts absents et répertoires temporaires retirés. Restent la frame synthétique traitée et l’observation persistée dans la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. Détails : `skills/gpu-inference/SKILL.md`. -- 2.54.1 From 7b816d64421f149ce412d6d518fc4d433d8b1623 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 20:09:27 +0100 Subject: [PATCH 37/40] test(live): validate audio over real WHEP --- skills/webrtc-live/SKILL.md | 4 ++ .../Heimdall.E2E.Tests/Pages/LiveViewTests.cs | 72 +++++++++++++------ todo.md | 2 +- 3 files changed, 57 insertions(+), 21 deletions(-) diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md index 746c07d..314fbed 100644 --- a/skills/webrtc-live/SKILL.md +++ b/skills/webrtc-live/SKILL.md @@ -89,3 +89,7 @@ Record LAN browser and external TURN runs independently. Focused API/Web ticket/ ## Synthetic audio acceptance Run a disposable Compose source build plus a synthetic H.264+sine RTSP publisher. The source-built Agent tests must assert the relay command maps `0:a:0?`, converts audio to Opus, and does not disable audio. The Compose stream must be pulled from the relay and inspected to confirm H.264 video and Opus audio. Also run the authenticated WHEP browser flow and assert its media stream contains both tracks; no physical camera or external TURN claim follows from this recipe. Build app images with unique tags and remove/verify those exact tags in the same EXIT cleanup trap, or explicitly record `local image tags: none` for SDK/upstream-only test runs. + +`LiveViewTests.Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay` uses its fake peer by default for an isolated UI contract test. For the real-media path, set `HEIMDALL_TEST_LIVE_WHEP_URL` to the disposable MediaMTX `/path/whep` endpoint before running the same test. It then uses Chromium's real RTCPeerConnection and waits for a decoded video frame (`videoWidth > 0`) plus a live audio track. Pair this with a project-isolated MediaMTX service and synthetic H.264/Opus publisher, configured with a loopback WHEP port, a matching loopback ICE UDP candidate, and wildcard origins only on the throwaway test server. The test still mocks only Central's short-lived read-session response; the earlier Central permission/ticket test remains the evidence for that boundary. Teardown must remove and verify all project resources and any exact local image tags. + +On 5 November 2026, disposable project `hmd-whep-audio-1793905588-381987` ran MediaMTX plus an animated 640×360 H.264 and 48 kHz sine/Opus publisher. The source-built Web/E2E assembly used the real `live-view.js` and Chromium against `http://127.0.0.1:/live/whep`; `LiveViewTests` passed 1/1 with a decoded video frame, live audio track, and muted autoplay. Central's session response was stubbed, so this proves browser/media negotiation and decoding, not production auth or external ICE/TURN. Cleanup verified zero project containers, volumes and networks; no local images were built and the temporary Compose file was removed. diff --git a/tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs b/tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs index d264c88..5b8c1b6 100644 --- a/tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs +++ b/tests/Heimdall.E2E.Tests/Pages/LiveViewTests.cs @@ -13,6 +13,8 @@ public sealed class LiveViewTests : E2ETestBase public async Task Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay() { var cameraId = Guid.NewGuid(); + var realWhepUrl = Environment.GetEnvironmentVariable("HEIMDALL_TEST_LIVE_WHEP_URL"); + var useRealMedia = !string.IsNullOrWhiteSpace(realWhepUrl); await Page.RouteAsync("**/api/live-media/**", async route => { var request = route.Request; @@ -24,7 +26,7 @@ public sealed class LiveViewTests : E2ETestBase ContentType = "application/json", Body = JsonSerializer.Serialize(new { - url = $"{BaseUrl}/media/{cameraId:D}/whep", + url = useRealMedia ? realWhepUrl : $"{BaseUrl}/media/{cameraId:D}/whep", token = "synthetic-read-ticket", sessionId = Guid.NewGuid(), iceServers = Array.Empty() @@ -35,19 +37,23 @@ public sealed class LiveViewTests : E2ETestBase await route.FulfillAsync(new() { Status = (int)HttpStatusCode.NoContent }); }); - await Page.RouteAsync("**/media/**/whep", route => route.FulfillAsync(new() + if (!useRealMedia) { - Status = (int)HttpStatusCode.Created, - ContentType = "application/sdp", - Headers = new Dictionary { ["Location"] = "/media/session-resource" }, - Body = "v=0\r\n" - })); - await Page.RouteAsync("**/media/session-resource", route => route.FulfillAsync(new() - { - Status = (int)HttpStatusCode.NoContent - })); + await Page.RouteAsync("**/media/**/whep", route => route.FulfillAsync(new() + { + Status = (int)HttpStatusCode.Created, + ContentType = "application/sdp", + Headers = new Dictionary { ["Location"] = "/media/session-resource" }, + Body = "v=0\r\n" + })); + await Page.RouteAsync("**/media/session-resource", route => route.FulfillAsync(new() + { + Status = (int)HttpStatusCode.NoContent + })); + } await Page.GotoAsync($"{BaseUrl}/login"); + if (!useRealMedia) await Page.EvaluateAsync(""" () => { window.__liveViewTransceivers = []; @@ -71,30 +77,56 @@ public sealed class LiveViewTests : E2ETestBase """); var result = await Page.EvaluateAsync(""" - async cameraId => { + async options => { + const { cameraId, useRealMedia } = options; const video = document.createElement('video'); video.dataset.liveCamera = cameraId; - video.play = async () => { window.__liveViewPlayCalled = true; }; + if (!useRealMedia) + video.play = async () => { window.__liveViewPlayCalled = true; }; document.body.append(video); const live = await import('/js/live-view.js'); await live.start(cameraId, video); + if (useRealMedia) { + await new Promise((resolve, reject) => { + const deadline = setTimeout(() => reject(new Error('Timed out waiting for decoded WebRTC audio/video')), 20000); + const timer = setInterval(() => { + if (video.videoWidth > 0 && video.srcObject?.getAudioTracks().some(track => track.readyState === 'live')) { + clearInterval(timer); + clearTimeout(deadline); + resolve(); + } + }, 100); + }); + } const value = { transceivers: window.__liveViewTransceivers, tracks: window.__liveViewTracks, + audioTracks: video.srcObject?.getAudioTracks().length ?? 0, + videoTracks: video.srcObject?.getVideoTracks().length ?? 0, + videoWidth: video.videoWidth, muted: video.muted, playCalled: window.__liveViewPlayCalled }; await live.stop(cameraId); return value; } - """, cameraId.ToString("D")); + """, new { cameraId = cameraId.ToString("D"), useRealMedia }); - result.GetProperty("transceivers").EnumerateArray().Select(x => x.GetProperty("kind").GetString()) - .ShouldBe(new[] { "video", "audio" }); - result.GetProperty("transceivers").EnumerateArray().ShouldAllBe(x => - x.GetProperty("direction").GetString() == "recvonly"); - result.GetProperty("tracks").EnumerateArray().Select(x => x.GetString()).ShouldBe(new[] { "video", "audio" }); + if (useRealMedia) + { + result.GetProperty("audioTracks").GetInt32().ShouldBeGreaterThan(0); + result.GetProperty("videoTracks").GetInt32().ShouldBeGreaterThan(0); + result.GetProperty("videoWidth").GetInt32().ShouldBeGreaterThan(0); + } + else + { + result.GetProperty("transceivers").EnumerateArray().Select(x => x.GetProperty("kind").GetString()) + .ShouldBe(new[] { "video", "audio" }); + result.GetProperty("transceivers").EnumerateArray().ShouldAllBe(x => + x.GetProperty("direction").GetString() == "recvonly"); + result.GetProperty("tracks").EnumerateArray().Select(x => x.GetString()).ShouldBe(new[] { "video", "audio" }); + result.GetProperty("playCalled").GetBoolean().ShouldBeTrue(); + } result.GetProperty("muted").GetBoolean().ShouldBeTrue(); - result.GetProperty("playCalled").GetBoolean().ShouldBeTrue(); } } diff --git a/todo.md b/todo.md index 58aefbd..57c1331 100644 --- a/todo.md +++ b/todo.md @@ -47,7 +47,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. -- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Le 5 novembre, le relais Agent passe aussi une piste audio source facultative en Opus : tests `LiveCameraRelayServiceTests` 2/2 sur source copiée et restore locked en SDK Compose, et recette MediaMTX/FFmpeg synthétique `hmd-webrtc-audio-1793903836-366262` confirme par ffprobe les flux `h264,video` et `opus,audio`. Aucun tag local créé; teardown vérifié zéro conteneur/volume/réseau, sources temporaires supprimées. L’UI réserve maintenant audio+vidéo en réception et démarre muette. `LiveViewTests.Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay` passe 1/1 sous Chromium avec un faux RTCPeerConnection qui injecte les deux pistes; compilation E2E source .NET 10 réussie sans avertissement. Cela vérifie la négociation et l’UI, pas le décodage du flux audio sur WHEP réel. Caméra physique, LAN et TURN externe, piste audio navigateur sur MediaMTX, PTZ, transcodage vidéo et budget latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; étendre live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ et libération des ressources. Le vertical vidéo initial fournit le relais Agent FFmpeg H.264, les tickets MediaMTX publish/read caméra-scopés, leur revalidation des droits et le lecteur WHEP CameraDetail. Le 5 novembre 2026, une recette Compose jetable construite depuis la source a validé bootstrap Central/site, Agent et caméra RTSP synthétique assignée, puis le `live-view.js` réel dans Chromium a décodé une image 640×360 (1 piste). Suppression WHEP 200 et release Central 204; désactivation API caméra : processus FFmpeg relay 1→0. Callbacks MediaMTX acceptent le ticket valide et refusent action/path/protocole altérés et ticket forgé (401); caméra inconnue refusée. Les journaux vérifiés ne contiennent aucun jeton, mot de passe ou URL RTSP. Cette recette a corrigé les origines CORS par env MTX et aligné le port UDP ICE annoncé/publié. Compose `hmd-wrtc-75d1f49f` a été arrêté avec `down --volumes --remove-orphans`, puis vérifié à 0 conteneur/volume/réseau; cache secrets supprimé. Le 5 novembre, le relais Agent passe aussi une piste audio source facultative en Opus : tests `LiveCameraRelayServiceTests` 2/2 sur source copiée et restore locked en SDK Compose, et recette MediaMTX/FFmpeg synthétique `hmd-webrtc-audio-1793903836-366262` confirme par ffprobe les flux `h264,video` et `opus,audio`. Aucun tag local créé; teardown vérifié zéro conteneur/volume/réseau, sources temporaires supprimées. L’UI réserve maintenant audio+vidéo en réception et démarre muette. Le 5 novembre, `LiveViewTests.Live_view_negotiates_audio_and_video_and_starts_muted_for_autoplay` a aussi passé 1/1 sous Chromium face au vrai WHEP MediaMTX du Compose `hmd-whep-audio-1793905588-381987`, alimenté par H.264 640×360 animé + Opus 48 kHz : videoWidth>0, piste audio vivante, lecteur muet. L’assembly E2E source a été restauré en locked mode et compilé sans avertissement. La réponse de session Central était mockée; les droits/tickets Central restent couverts par l’acceptance initiale. Caméra physique, LAN et TURN externe, piste audio navigateur sur MediaMTX, PTZ, transcodage vidéo et budget latence mesuré restent ouverts. Voir `skills/webrtc-live/SKILL.md`. - [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construite depuis cette source : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu. Le quota Central est maintenant configurable par `RECORDING_STORAGE_QUOTA_MAX_BYTES` (défaut 1 TiB), validé au démarrage; les uploads dépassant la limite répondent 507 et leur objet est supprimé. Test PostgreSQL concurrent ciblé passé 1/1 : quota 32 octets, course même RecordingId avec clé d'objet GUID unique et nettoyage du doublon, puis course de deux segments donnant un succès + 507, somme persistée égale au quota et retry idempotent. Ajout local : `AgentRecordingServiceTests.UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity` simule HTTP 503 puis 204 et vérifie conservation du MP4 en échec, URL d’idempotence et clé identiques à la reprise, puis suppression uniquement après succès. Le 5 novembre 2026, FFmpeg mappe aussi la piste audio présente (facultative) et l’encode en AAC 128 kbit/s; le test des arguments couvre la sélection audio et les options MP4. Implémentation locale. Le 5 novembre 2026, recette Compose jetable `hmd-recording-audio-1793884180-10354` a compilé/restauré en mode locked cette source dans SDK 10.0.100 et passé `AgentRecordingServiceTests` 2/2; une source FFmpeg synthétique testsrc+sine a produit des segments MP4 dont ffprobe a confirmé H.264 vidéo + AAC audio. Cleanup EXIT avec `down --volumes --remove-orphans`; requêtes après recette : zéro conteneur, volume, réseau et tag local de projet. Aucun tag app local n’était créé; SDK/FFmpeg amont conservés. Deux premiers essais du harness (interpolation shell Compose puis ordre ffprobe/cache NuGet) ont aussi exécuté cleanup et ont laissé zéro ressource de projet. Cela valide les arguments et le muxer synthétique, pas le chemin Agent live RTSP complet ni les codecs caméra réels. Le 5 novembre 2026, recette Compose jetable construite depuis cette source (`hmd-rec-e2e-1793888149-9799`) : Central/PostgreSQL, Agent compilé avec restore locked, MediaMTX et FFmpeg synthétique H.264+sine/AAC; bootstrap Admin/site, inscription Agent, caméra Online+enregistrement activé, affectation et upload live validés. Le contenu MP4 reçu a été inspecté par ffprobe (H.264 video + AAC audio); accès autorisé Range `bytes 0-15` = HTTP 206/16 octets, anonyme = 401. Trap : teardown `down --volumes --remove-orphans`, 0 conteneur/volume/réseau, tags uniques Central et Agent retirés puis vérifiés absents; image ffprobe amont partagée conservée. Deux runs initiaux ont révélé/corrigé des erreurs du harness (option Agent Central URL/HTTP de test, attente mal contrôlée, interprétation du 401 attendu et ffprobe manquant sur hôte); leurs ressources/tags ont aussi été vérifiés absents. La source caméra et les codecs sont synthétiques, aucune caméra réelle validée. La suite Python CI avait signalé que le chemin `RecordingQuotaGuard` manquait de l’allowlist de l’exception advisory-lock malgré son commentaire et le test relationnel existants; entrée exacte et rationale ajoutées à la policy. Compose source jetable `hmrecquota_1793868155_7234` : build réussi, `healthz=200`, bootstrap-status setupRequired=true avec quota 32, teardown vérifié 0 conteneur/0 volume/0 réseau; secrets temporaires supprimés. Le 5 novembre, `RecordingEventAssociationTests.SegmentUpload_AssociatesOnlyEventsInItsHalfOpenTimeRange` passe 1/1 dans le projet Compose jetable `hmd-recording-event-1793895250-6481` contre PostgreSQL : timestamps avant, au début, dans le segment, à la fin et après; seules les deux occurrences dans `[début, fin)` sont associées. Teardown vérifié 0 conteneur/volume/réseau et aucun tag d’image local; images SDK/PostgreSQL upstream conservées. Le 5 novembre 2026, la capture événementielle est implémentée : opt-in `EventRecordingEnabled` séparé du continu dans CameraDetail/API et configuration Agent, déclenchement sur Motion/Person/Vehicle/UnknownPerson/Face/Plate, fenêtre post-roll configurable (5–300 s, défaut 30), marqueur atomique borné à un fichier par caméra, reprise après redémarrage, suppression à désactivation/caméra désactivée/désaffectation; événements arrivant avant ou après l’upload sont associés. Compose jetable source-build `hmd-event-e2e-1793899172-25617` (Central, PostgreSQL, Agent, MediaMTX, FFmpeg) : Agent inscrit par le vrai jeton site, flux RTSP synthétique H.264/AAC, MotionDetected=1, enregistrement continu désactivé, segment reçu=1 et événement lié=1; redémarrage Agent durant le post-roll puis second segment reçu=2; désactivation API puis stabilisation à 2 sans nouvel upload. Les seuils de mouvement synthétiques sont abaissés pour rendre l’événement déterministe; l’inférence d’objets et la caméra physique ne sont pas validées. Images construites depuis cette source avec restore .NET 10 locked : `heimdall:hmd-event-e2e-1793899172-25617-central` et `heimdall-agent:hmd-event-e2e-1793899172-25617-agent`, supprimées et vérifiées absentes; zéro conteneur/volume/réseau après teardown. `RecordingTriggerStoreTests` 3/3 via SDK Compose `hmd-trigger-unit-1793899683-6893`, aucun tag local, zéro ressource. `RecordingEventAssociationTests` PostgreSQL 1/1 vérifie bornes demi-ouvertes et événement créé après upload; avant modification ciblée, suites Agent/Application/Web 29/29, 14/14, 8/8. Le 5 novembre, la suite Agent ciblée `RecordingTriggerStoreTests|DetectionReporterServiceTests` passe 19/19 depuis la source via SDK Compose `hmd-event-agent-test-1793903398-364902` après restore locked; elle couvre maintenant le trigger durable même si l’outbox rejette un payload trop volumineux. Aucun tag local créé; cleanup vérifié 0 conteneur/volume/réseau et sources temporaires supprimées. FEAT-02 reste ouvert pour validation avec caméras/codecs réels. Skill : `skills/video-recording/SKILL.md`. - [ ] **FEAT-03 / UI-02** Chaîne partielle P2 : l’UI caméra propose une lecture OCR de recadrage de plaque déclenchée explicitement; Central local Tesseract, option `PlateOcr:Enabled` désactivée par défaut et exposée via PLATE_OCR_ENABLED dans Compose core/prod et les installateurs Linux/Windows (false en installation neuve, valeur conservée en mise à jour), limites fichier/dimensions/délai et suppression du crop temporaire. Rebuild source demandé par le Compose courant bloqué plus de 8 min sur BuildKit avant tout conteneur; pour exercer le câblage, un Compose jetable distinct hmd-ocr-env-safe-1793874420 a utilisé l’image Central déjà buildée depuis le code OCR de cette branche : health=healthy avec valeur effective false par défaut, puis true après override/recréation; override Sentry__Dsn vide; teardown 0/0/0. Un run initial sans cet override a envoyé des événements de logs EF vers GlitchTip; seuls secrets/DB synthétiques, aucun compte réel. Le Compose de cette recette a donc validé le mapping, mais pas un rebuild final de l’image depuis ce checkout. Tests ciblés : `PlateOcrTests` 4/4, `CameraDetailTests` 6/6, `PlateRecognitionControllerTests` 1/1, `ConfirmPlateAssociationHandlerTests` 4/4 et confirmation UI/API 2/2. Acceptance Compose source `hmd-plate-20261105094933-31487` : bootstrap admin/site/caméra synthétiques, OCR API multipart `AB-123-CD` confiance 0,912, événement visible sur page 1 de l’historique API, image JPEG invalide rejetée 400; vérification PostgreSQL observation/événement non liés, sans snapshot, crop temporaire absent. Acceptance du workflow de confirmation dans `hmd-plate-link-1793880442-bff1ca` : OCR `AB-123-CD`, véhicule incompatible rejeté 422, observation et événement encore non liés avant l’action opérateur, confirmation explicite 200, deux liens persistés dans PostgreSQL, anonyme rejeté 401. Le central a été construit avec un tag dédié; teardown 0 conteneur/volume/réseau et image exacte supprimée/vérifiée absente. Deux essais précédents ont échoué uniquement dans le harness (attente du mauvais healthcheck puis casse/majuscules SQL); leurs projets, volumes, réseaux et images dédiés ont également été supprimés et vérifiés absents. La création de l’admin a aussi provoqué le contrôle HaveIBeenPwned existant (seul mot de passe synthétique, échange k-anonymity; la recette n’était pas strictement hors réseau). Pas de caméra/donnée réelle; pas de test UI navigateur ni d’exactitude hors fixture. Le 5 novembre 2026, `CleanupLicensePlatesJob` purge aussi après 30 jours les événements `LicensePlateDetected` et leurs snapshots : objets supprimés d’abord sur la destination persistée; événements à provenance absente/incomplète conservés avec warning. Tests SQLite 3/3 couvrent conservation des événements récents/non OCR, suppression des snapshots avant les lignes et maintien de la ligne en cas d’échec storage. Test PostgreSQL de traduction EF et suppression 1/1 dans la recette Compose `hmd-plate-retention-pg-1793885533-16210`; restore locked depuis le source, credentials générés, volumes dédiés, cleanup 0/0/0. La recette ne construit pas d’image Heimdall et conserve les bases Postgres/SDK partagées. **Reste ouvert** : détection vidéo des plaques; inférence/reconnaissance faciale (poids/licences/provenance et contrat modèle non résolus, aucun poids inclus); validation externe de la durée de rétention et revue privacy. Détails : `skills/vision-identity/SKILL.md`. - [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel d’inventaire restent distincts. L’Agent a un runtime CUDA amd64 optionnel à versions/digest épinglés, un overlay de développement NVIDIA, un manifeste d’image GPU dans le manifeste ECDSA, un choix CPU/CUDA dans l’installateur et la conservation du variant aux mises à jour; CPU reste le défaut. Les restores CPU/GPU verrouillés, builds de la première image CPU/GPU, 4 tests de sélection/fallback initiaux, 2 tests de signature, l’inférence CPU réelle avec le package GPU et 10 tests Web `SiteDetailTests` passent. L’acceptation offline de release signée passe aussi (10 assets, sommes/signature, six pushes simulés, sans services distants). Le 4 novembre 2026, l’image GPU initiale a exposé un crash natif ONNX 139 sans matériel NVIDIA. Le code vérifie maintenant la détection NVIDIA avant toute énumération native; 5 tests Agent ciblés passent. Le 5 novembre, le Dockerfile GPU post-correctif a été reconstruit depuis la source et son Compose rendu vérifie CPU sans réservation NVIDIA, variant GPU, overlay GPU et state-init sur la même image. Central/PostgreSQL jetables ont été construits, healthz a répondu 200, et bootstrap Admin/site avec token synthétique a réussi. Acceptation Agent locale complétée le 5 novembre : image CUDA reconstruite depuis ce checkout avec restore verrouillé, lancement sans device GPU sur réseau isolé et état tmpfs; détection « No GPU detected », fallback et modèle YOLO chargés avec `CPUExecutionProvider`, enregistrement et heartbeat simulés (HTTP 200/204), healthz 200. Le test `RealOnnx_CpuModel_ProcessesFullHdImage` passe aussi avec `HeimdallOnnxRuntime=GPU` (1/1). Le mock ne simule pas les API de configuration/jobs, donc aucune frame n’a traversé la boucle Agent/Central; ce n’est pas une preuve d’inférence end-to-end depuis caméra synthétique. Conteneur, tag d’image dédié et écouteur mock supprimés/vérifiés absents. La fixture Central a d’abord fourni `DATABASE_URL` au format URI au lieu du format Npgsql attendu; cette seule erreur de fixture a déclenché un rapport GlitchTip, sans données de production ni secret, puis le DSN a été désactivé avant le redémarrage. Le projet jetable `hmgpu96cc65b9` a ensuite été supprimé et vérifié à 0 conteneur/0 volume/0 réseau. Le 5 novembre, deux essais de boucle complète Compose (`hmgpu-loop-e9377c0b`, `hmgpu-loop-929b670e`) ont construit l’image Central et l’image GPU depuis ce checkout avec tags uniques; Buildx s’est toutefois bloqué après export et avant création des services, donc aucun frame/job/observation persisté n’a été validé. Les deux essais ont été démontés avec 0 conteneur/volume/réseau, tags exacts absents et répertoires temporaires retirés. Restent la frame synthétique traitée et l’observation persistée dans la boucle Agent/Central, puis l’exécution CUDA sur NVIDIA réel. Détails : `skills/gpu-inference/SKILL.md`. -- 2.54.1 From cb03c00b07f664fa55a3372f7d8bffa943772fe9 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 21:40:00 +0100 Subject: [PATCH 38/40] test: configure recordings set in event handler fixture --- skills/analysis-job-pipeline/SKILL.md | 2 ++ .../Handlers/Events/CreateEventHandlerTests.cs | 1 + todo.md | 2 ++ 3 files changed, 5 insertions(+) diff --git a/skills/analysis-job-pipeline/SKILL.md b/skills/analysis-job-pipeline/SKILL.md index 0b4d037..62f822d 100644 --- a/skills/analysis-job-pipeline/SKILL.md +++ b/skills/analysis-job-pipeline/SKILL.md @@ -26,6 +26,8 @@ Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet 5. Tear down that exact Compose project, verify zero project containers/volumes/networks, remove every source-built image tag from this recipe and verify each exact tag is absent. Retain shared Postgres/.NET base images. Never use broad prune commands. 6. Keep hardware, camera-stream inference, and real multi-Agent deployment claims separate from synthetic database/API acceptance. +For event-handler unit tests, initialize every queried set on the `IApplicationDbContext` substitute with `MockDbSetHelper`, including empty optional sets such as `Recordings`. An unconfigured NSubstitute `DbSet` throws from EF's `IQueryable.Provider` when the handler applies `AsNoTracking` or async LINQ. Use PostgreSQL integration tests for provider translation and persistence behavior; this unit fixture is only for handler branching and notification behavior. + ## Current local acceptance evidence On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference. diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs index 99ffd9f..3595017 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Events/CreateEventHandlerTests.cs @@ -31,6 +31,7 @@ public class CreateEventHandlerTests var occuredAt = DateTime.UtcNow; _context.Cameras.Returns(MockDbSetHelper.CreateFor([camera])); + _context.Recordings.Returns(MockDbSetHelper.CreateFor()); var cameraEventsDb = new CameraAwareDbSet([], id => id == cameraId ? camera : null); _context.CameraEvents.Returns(cameraEventsDb); _context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); diff --git a/todo.md b/todo.md index 57c1331..78a017d 100644 --- a/todo.md +++ b/todo.md @@ -18,6 +18,8 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant ## P1 — parcours caméra, agent et données +- [x] Corriger la fixture unitaire `CreateEventHandlerTests` révélée rouge par la CI de la PR #138 : elle ne configurait pas `Recordings`, requis par la requête EF du handler. Le test initialise maintenant un `MockDbSet` vide; procédure ajoutée à `skills/analysis-job-pipeline/SKILL.md`. La CI PR reste à relancer pour confirmer l’ensemble des suites. + - [x] **AUTH-BOOTSTRAP** L’assistant `/setup` ne crée le premier compte que sur une base vide et lui attribue Admin dans une transaction PostgreSQL sérialisable; l’UI login redirige vers l’assistant au premier lancement. L’inscription anonyme et l’ancienne route `register-admin` renvoient 404; les comptes suivants passent par l’UI `/users` et l’API protégée `Admin.Users`. Recette Compose jetable finale du 4 novembre 2026 : statut initial ouvert → premier Admin → statut fermé → création d’utilisateurs protégée; vérification de la route setup, refus anonyme et suppression des deux anciennes routes. Tests PostgreSQL intégration complets 161/161; tests E2E AuthFlow/UI utilisateur réussis (résultats notés dans USER-RBAC ci-dessous). Le bootstrap concurrent reste couvert par les tests PostgreSQL dédiés. - [x] **IDENTITY-HARDENING** 2FA en deux étapes; changements de mot de passe/email/rôles/verrouillage/2FA révoquent les sessions; résultats Identity contrôlés, réponses génériques et erreurs sensibles exclues des journaux. ASP.NET Core Identity est isolé dans Infrastructure (`IdentityAppUser`, `IdentityAppRole`, `IdentityAccountService`); Domain ne référence plus Identity ni ses packages, Application dépend du port `IIdentityAccountService`, et les requêtes EF d’identité restent dans Infrastructure. `AppDbContext` conserve le modèle et le schéma existants; migration `20261104095135_MoveIdentityPersistenceToInfrastructure` est sans opération. Tests PostgreSQL ont révélé puis vérifié la correction du `SecurityStamp` recopié après création et d’une course de consommation concurrente des codes de secours (la requête perdante ne modifie plus le compteur pendant la rotation du stamp gagnante). Build solution sans avertissement; Application 517/517, Infrastructure 281/281, Integration PostgreSQL 161/161, Web 412/412, E2E UI bootstrap/gestion 15/15. Compose construit depuis la source; bootstrap initial, création utilisateur, confirmation, rôles/permissions, révocation JWT et dernier Admin vérifiés; nettoyage du projet, de ses volumes et réseau confirmé. Le test Compose a exposé le décalage SDK/runtime de l’image Docker épinglée; les digests SDK/ASP.NET ont été actualisés dans les Dockerfiles et les conteneurs CI; le restore verrouillé + publish passent dans l’image. Le run PR #693 a passé toutes les suites unitaires, PostgreSQL (161) et Web (412), mais le restore de l’outil Chromium autonome a échoué sur les empreintes SDK 10.0.14. L’installation utilise maintenant le Playwright CLI déjà inclus dans l’assemblage E2E, sans projet de restore séparé; validation locale puis nouveau run PR requis avant fusion. - [x] **USER-RBAC** Premier Admin et comptes suivants créés via leurs écrans dédiés; l’UI `/users` liste, crée, édite, assigne les rôles, confirme l’email, verrouille/déverrouille, réinitialise le mot de passe et supprime. L’ancienne API de création Admin hors UI a été retirée. Les claims Identity persistés alimentent maintenant les droits effectifs; `/admin/claims` modifie les permissions Supervisor/Viewer et le rôle Admin reste immuable. Les changements de rôle/droits renouvellent les `SecurityStamp`, invalident JWT/cookies/refresh de la cible et journalisent l’acteur. Les routes Users/Roles/Permissions appliquent leurs politiques; le dernier Admin déverrouillé ne peut pas être verrouillé ou déclassé, et sa suppression est refusée. E2E navigateur AuthFlow + gestion utilisateurs 15/15; tests Application 517/517, Infrastructure 281/281, Web 412/412 et PostgreSQL 161/161. Compose jetable construit depuis le code final : Viewer refusé sur API Admin, permission `Camera.Write` modifiée puis effective sur `/api/cameras`, ancien JWT refusé, dernier Admin protégé; nettoyage conteneurs/volumes/réseau vérifié. Les définitions de rôles restent les trois rôles système (Admin fixe, Supervisor et Viewer configurables), sans création de rôles arbitraires. -- 2.54.1 From 361b37cecef2b0f3006b518d28a538cc26d75d9f Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 5 Nov 2026 21:57:22 +0100 Subject: [PATCH 39/40] test: dismiss PWA banner in browser acceptance --- skills/analysis-job-pipeline/SKILL.md | 2 ++ tests/Heimdall.E2E.Tests/E2ETestBase.cs | 3 +++ todo.md | 4 +++- 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/skills/analysis-job-pipeline/SKILL.md b/skills/analysis-job-pipeline/SKILL.md index 62f822d..560dcb4 100644 --- a/skills/analysis-job-pipeline/SKILL.md +++ b/skills/analysis-job-pipeline/SKILL.md @@ -28,6 +28,8 @@ Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet For event-handler unit tests, initialize every queried set on the `IApplicationDbContext` substitute with `MockDbSetHelper`, including empty optional sets such as `Recordings`. An unconfigured NSubstitute `DbSet` throws from EF's `IQueryable.Provider` when the handler applies `AsNoTracking` or async LINQ. Use PostgreSQL integration tests for provider translation and persistence behavior; this unit fixture is only for handler branching and notification behavior. +The shared Playwright `E2ETestBase.GotoWithCircuitAsync` dismisses the install-help banner after each navigation. Loopback is a secure browser context, so PWA UI appears in these tests and can intercept clicks on dialogs; browser E2E assertions should exercise the intended application controls after dismissing that unrelated notice. + ## Current local acceptance evidence On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference. diff --git a/tests/Heimdall.E2E.Tests/E2ETestBase.cs b/tests/Heimdall.E2E.Tests/E2ETestBase.cs index 00ef295..ac81274 100644 --- a/tests/Heimdall.E2E.Tests/E2ETestBase.cs +++ b/tests/Heimdall.E2E.Tests/E2ETestBase.cs @@ -63,6 +63,9 @@ public abstract class E2ETestBase : IAsyncLifetime // Give the circuit a moment to hydrate event handlers before we interact. // Increased delay to allow Blazor content to fully render. await Task.Delay(2000); + var pwaDismiss = Page.Locator(".pwa-install-notice .pwa-notice-dismiss"); + if (await pwaDismiss.IsVisibleAsync()) + await pwaDismiss.ClickAsync(); } /// diff --git a/todo.md b/todo.md index 78a017d..f29d4cc 100644 --- a/todo.md +++ b/todo.md @@ -18,7 +18,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant ## P1 — parcours caméra, agent et données -- [x] Corriger la fixture unitaire `CreateEventHandlerTests` révélée rouge par la CI de la PR #138 : elle ne configurait pas `Recordings`, requis par la requête EF du handler. Le test initialise maintenant un `MockDbSet` vide; procédure ajoutée à `skills/analysis-job-pipeline/SKILL.md`. La CI PR reste à relancer pour confirmer l’ensemble des suites. +- [x] Corriger la fixture unitaire `CreateEventHandlerTests` révélée rouge par la CI de la PR #138 : elle ne configurait pas `Recordings`, requis par la requête EF du handler. Le test initialise maintenant un `MockDbSet` vide. Le run #753 a aussi révélé que la bannière PWA du contexte loopback interceptait les dialogues Playwright; la fixture E2E la ferme après navigation. Ces précautions sont documentées dans `skills/analysis-job-pipeline/SKILL.md`; la CI PR reste à relancer pour confirmer l’ensemble des suites. - [x] **AUTH-BOOTSTRAP** L’assistant `/setup` ne crée le premier compte que sur une base vide et lui attribue Admin dans une transaction PostgreSQL sérialisable; l’UI login redirige vers l’assistant au premier lancement. L’inscription anonyme et l’ancienne route `register-admin` renvoient 404; les comptes suivants passent par l’UI `/users` et l’API protégée `Admin.Users`. Recette Compose jetable finale du 4 novembre 2026 : statut initial ouvert → premier Admin → statut fermé → création d’utilisateurs protégée; vérification de la route setup, refus anonyme et suppression des deux anciennes routes. Tests PostgreSQL intégration complets 161/161; tests E2E AuthFlow/UI utilisateur réussis (résultats notés dans USER-RBAC ci-dessous). Le bootstrap concurrent reste couvert par les tests PostgreSQL dédiés. - [x] **IDENTITY-HARDENING** 2FA en deux étapes; changements de mot de passe/email/rôles/verrouillage/2FA révoquent les sessions; résultats Identity contrôlés, réponses génériques et erreurs sensibles exclues des journaux. ASP.NET Core Identity est isolé dans Infrastructure (`IdentityAppUser`, `IdentityAppRole`, `IdentityAccountService`); Domain ne référence plus Identity ni ses packages, Application dépend du port `IIdentityAccountService`, et les requêtes EF d’identité restent dans Infrastructure. `AppDbContext` conserve le modèle et le schéma existants; migration `20261104095135_MoveIdentityPersistenceToInfrastructure` est sans opération. Tests PostgreSQL ont révélé puis vérifié la correction du `SecurityStamp` recopié après création et d’une course de consommation concurrente des codes de secours (la requête perdante ne modifie plus le compteur pendant la rotation du stamp gagnante). Build solution sans avertissement; Application 517/517, Infrastructure 281/281, Integration PostgreSQL 161/161, Web 412/412, E2E UI bootstrap/gestion 15/15. Compose construit depuis la source; bootstrap initial, création utilisateur, confirmation, rôles/permissions, révocation JWT et dernier Admin vérifiés; nettoyage du projet, de ses volumes et réseau confirmé. Le test Compose a exposé le décalage SDK/runtime de l’image Docker épinglée; les digests SDK/ASP.NET ont été actualisés dans les Dockerfiles et les conteneurs CI; le restore verrouillé + publish passent dans l’image. Le run PR #693 a passé toutes les suites unitaires, PostgreSQL (161) et Web (412), mais le restore de l’outil Chromium autonome a échoué sur les empreintes SDK 10.0.14. L’installation utilise maintenant le Playwright CLI déjà inclus dans l’assemblage E2E, sans projet de restore séparé; validation locale puis nouveau run PR requis avant fusion. @@ -46,6 +46,8 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant ## P2 — fonctionnalités et exploitation +- [ ] **NTFY-SITE-CREATE** La création d’un site depuis `/sites` doit persister le topic ntfy comme le fait sa modification. Le 5 novembre 2026, le défaut a été localisé au contrat `CreateSiteRequest` et au contrôleur : l’UI envoyait `ntfyTopic`, mais le DTO le rejetait et le contrôleur ne le transmettait pas au command. Correction ajoutée; le test d’intégration relit le site via l’API et vérifie le topic. À clôturer après tests et recette Compose jetable depuis cette source, avec teardown vérifié. Skill : `skills/site-ntfy-creation/SKILL.md`. + - [x] **Génération de l’installation Central** La PR #117 ajoute `install/install-server.sh` : le script interactif génère le Compose minimal Central + PostgreSQL et un `.env` protégé avec secrets aléatoires, puis propose de préparer/démarrer les Compose des services optionnels. Il lit l’image fixe Docker Hub dans le script; les intégrations applicatives restent configurées dans l’IHM. La PR a passé syntaxe Bash, `git diff --check`, les suites CI, les builds/scans des deux images et `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Les commandes bootstrap Bash/PowerShell sans clone et leur validation réelle sont suivies dans l’item P1 ci-dessus. - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. Acceptation Compose source passée le 4 novembre 2026 avec projet jetable : PostgreSQL et Central sains, `/healthz`, `/manifest.webmanifest`, `/service-worker.js` et `/offline.html` répondent 200 avec les types attendus; conteneurs, volumes, réseau et secrets temporaires supprimés. Restent l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. -- 2.54.1 From 1ac10ee3a28491ee62e06dbd46a06a9ce20ca1de Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 6 Nov 2026 07:34:38 +0100 Subject: [PATCH 40/40] Complete remaining Heimdall PR acceptance --- docker/Dockerfile | 5 ++- docker/Dockerfile.agent | 5 ++- docker/Dockerfile.agent.gpu | 4 +- skills/agent-runtime-acceptance/SKILL.md | 6 +++ skills/agent-update-acceptance/SKILL.md | 8 ++++ skills/analysis-job-pipeline/SKILL.md | 3 ++ skills/central-auto-updates/SKILL.md | 3 ++ skills/site-ntfy-creation/SKILL.md | 14 ++++++ .../Services/AnalysisJobPollingService.cs | 13 ++++-- .../Services/LogUploadService.cs | 13 +++++- src/Heimdall.Application/DTOs/SiteDto.cs | 2 +- .../Controllers/AgentsController.cs | 2 +- .../Controllers/SitesController.cs | 2 +- src/Heimdall.Web/Heimdall.Web.csproj | 1 + src/Heimdall.Web/Program.cs | 8 +++- .../AnalysisJobPollingServiceTests.cs | 40 +++++++++++++++++ .../LogBufferServiceTests.cs | 17 +++++++ .../Controllers/AgentLogsControllerTests.cs | 45 +++++++++++++++++++ .../Controllers/SitesControllerTests.cs | 13 ++++-- todo.md | 6 +++ 20 files changed, 196 insertions(+), 14 deletions(-) create mode 100644 skills/site-ntfy-creation/SKILL.md create mode 100644 tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs diff --git a/docker/Dockerfile b/docker/Dockerfile index 1801e0e..272d0ee 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -10,7 +10,10 @@ RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee WORKDIR /app -RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng && rm -rf /var/lib/apt/lists/* +RUN apt-get update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng \ + && rm -rf /var/lib/apt/lists/* ENV ASPNETCORE_URLS=http://+:8080 COPY --from=build /out/ ./ EXPOSE 8080 diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent index c04d3d0..dd6a502 100644 --- a/docker/Dockerfile.agent +++ b/docker/Dockerfile.agent @@ -12,7 +12,10 @@ RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-rest FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee WORKDIR /app -RUN apt-get update -qq && apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata && rm -rf /var/lib/apt/lists/* +RUN apt-get update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata \ + && rm -rf /var/lib/apt/lists/* RUN install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall ENV ASPNETCORE_URLS=http://127.0.0.1:8080 COPY --from=build /out/ ./ diff --git a/docker/Dockerfile.agent.gpu b/docker/Dockerfile.agent.gpu index fac6582..40e86ac 100644 --- a/docker/Dockerfile.agent.gpu +++ b/docker/Dockerfile.agent.gpu @@ -18,7 +18,9 @@ ENV DOTNET_ROOT=/usr/share/dotnet \ LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu \ ASPNETCORE_URLS=http://127.0.0.1:8080 \ Agent__InferenceExecutionProvider=CUDA -RUN apt-get update -qq && apt-get install -y --no-install-recommends \ +RUN apt-get update -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ ca-certificates ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \ && rm -rf /var/lib/apt/lists/* \ && install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall diff --git a/skills/agent-runtime-acceptance/SKILL.md b/skills/agent-runtime-acceptance/SKILL.md index de5df73..1d3d8e8 100644 --- a/skills/agent-runtime-acceptance/SKILL.md +++ b/skills/agent-runtime-acceptance/SKILL.md @@ -15,6 +15,12 @@ Read `AGENTS.md`, the Agent item in `todo.md`, and `skills/heimdall-dotnet/SKILL - `FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt` uses an in-process Kestrel Central simulator: config GET is served once; ACK receives 503 then 204; both posts must carry the same digest; the camera snapshot change event fires once; and Central records one successful ACK. `HEIMDALL_ACK_FIXTURE_PORT` pins the listener for Compose, while the API key fixture can be injected through `HEIMDALL_ACK_FIXTURE_API_KEY`. - Also retain the SignalR reconnect test that proves rejoin, full replacement (including removals), and applied values. +## Central log upload contract + +- Agent log levels must use the exact `AgentLogLevel` names accepted by Central's parser: `Information` and `Warning` (not the common aliases `Info`/`Warn`), alongside `Trace`, `Debug`, `Error`, and `Critical`. +- Keep `ToCentralLevel_MapsMicrosoftNamesToAgentContract` asserting both the emitted name and that Central's enum parser accepts it at the corresponding severity. +- Agent logging is API-key authenticated. A source-built disposable Compose check can register a synthetic Agent, submit one entry at each severity to `/api/agents/{id}/logs`, and read them back through the authorized Central log query. Keep generated credentials and project resources isolated and clean up exact locally built tags per the Compose recipe. + ## Local checks ```bash diff --git a/skills/agent-update-acceptance/SKILL.md b/skills/agent-update-acceptance/SKILL.md index 13399f3..20d78c3 100644 --- a/skills/agent-update-acceptance/SKILL.md +++ b/skills/agent-update-acceptance/SKILL.md @@ -20,3 +20,11 @@ Use this skill when changing `install/install-agent.sh`, `install/install-agent. - For updates, exercise both successful and rejected signatures before installation. Preserve the previous release until the candidate has reported the expected version and stayed healthy for the configured stability interval. - Use a temporary install root and fake runtime for local failure/rollback tests. Never point these tests at `/usr/local`, a real systemd service, production credentials, or an installed Agent state directory. - Report Linux and Windows real-host install/update/rollback as open until each OS has been exercised with a real service and the expected signing configuration. + +## Central installer asset delivery + +- `Heimdall.Web.csproj` publishes the Linux/Windows Agent installers and their supervisors under `wwwroot/install/`; `Program.ConfigureMiddleware` serves them through ASP.NET Core static files. +- ASP.NET Core's default MIME table does not recognize `.py`. Add `.py` to a `FileExtensionContentTypeProvider` explicitly or `/install/agent-supervisor.py` returns 404 despite being present in `wwwroot`. +- For changes to these assets or static-file configuration, build Central from the current source in a disposable Compose project and GET `/install/install-agent.sh` and `/install/agent-supervisor.py`. Require HTTP 200 and byte-for-byte equality with their source files. Also require `/healthz` healthy. +- Follow `skills/compose-disposable-recipe/SKILL.md`: use generated credentials, isolated ports/project volumes/network, a unique Central image tag, and an EXIT trap installed before build. Verify all project containers, volumes, and networks are gone and remove/verify absence of the exact local image tag. Keep shared base images. +- A successful local acceptance proves the source-built Central serves the files; it does not prove a deployed Central image has been rebuilt or restarted. Confirm deployed endpoints separately before calling an incident resolved. diff --git a/skills/analysis-job-pipeline/SKILL.md b/skills/analysis-job-pipeline/SKILL.md index 560dcb4..70a98a6 100644 --- a/skills/analysis-job-pipeline/SKILL.md +++ b/skills/analysis-job-pipeline/SKILL.md @@ -16,6 +16,7 @@ Read `AGENTS.md`, the PIPE-01/02 entry in `todo.md`, and `skills/heimdall-dotnet - The Web request whitelist, Central scheduler whitelist/capability requirements, and Agent parser must agree. The Agent accepts enum names and numeric enum values on the wire. Reject unsupported kinds instead of recording a successful empty result. - Face and plate recognition have separate model/license/privacy requirements; anomaly and full-scene analysis are not implemented. Do not advertise them as available or map them to generic object detection. - Jobs stay assigned to the Agent currently responsible for the camera. Keep the attempt ID, atomic claims, retries and late-result rejection intact when adding types. +- Result delivery retries transport failures, timeouts and HTTP 5xx with bounded backoff. A 409/404 attempt is no longer current and stops immediately; other HTTP 4xx responses are permanent for that submission and must also stop immediately so a bad result cannot block the Agent's next poll. Log the status code and job ID only; do not read or log Central response bodies. ## Required validation @@ -32,6 +33,8 @@ The shared Playwright `E2ETestBase.GotoWithCircuitAsync` dismisses the install-h ## Current local acceptance evidence +Result delivery has a focused Agent test: `SendResultAsync_DoesNotRetryPermanentClientRejection` returns after one HTTP 400. The supported result JSON uses web defaults (`classIndex`, not `ClassIndex`). The disposable source Compose acceptance below validates the Central job API and persisted result contract; keep transport retry behavior covered by the Agent HTTP-handler test. + On 5 November 2026, Agent selection tests passed 10/10, PostgreSQL scheduler tests passed 10/10, and the integration scenario for the two filtered types passed 2/2. Disposable source-built Compose project `hmd-analysis-1793881315-5ba569` bootstrapped synthetic Admin/site/Agent, registered and heartbeated the Agent, assigned a synthetic camera, rejected `MotionDetection` with HTTP 400, then created, dispatched, claimed, completed and read back persisted `PersonDetection` and `VehicleClassification` results. Teardown verified zero containers, volumes and networks and removed/verified absence of `heimdall:hmd-analysis-1793881315-5ba569-central`. This exercises scheduling and result contracts with synthetic detections, not video inference. Motion detection implementation and acceptance (5 November 2026): Agent compares two frames 500 ms apart from the active stream at 32×18 luminance; threshold is 0.12 per pixel and 2% changed pixels, and output is one normalized `motion` region. Central API/scheduler accept the type and its 1-core/512-MB/3-minute capability limits. Tests passed: Agent selection/comparison 13/13, PostgreSQL scheduler 27/27, Web/PostgreSQL API contract 3/3. Source-built disposable Compose project `hmd-motion-1793890915-22844` registered a real Agent container, started a synthetic moving RTSP stream, assigned the camera, created a MotionDetection job, and verified the Agent result with label `motion` and normalized bounds persisted in PostgreSQL. The project was torn down and verified at zero containers/volumes/networks; unique Central/Agent tags were removed and verified absent. Camera shake, exposure/lighting changes and representative real-camera thresholds remain unvalidated. diff --git a/skills/central-auto-updates/SKILL.md b/skills/central-auto-updates/SKILL.md index cd789e3..d8659d3 100644 --- a/skills/central-auto-updates/SKILL.md +++ b/skills/central-auto-updates/SKILL.md @@ -24,6 +24,7 @@ Use this skill when changing the Linux or Windows Central installer, its generat - Use the maintained `nickfedor/watchtower` image at an explicit version, `--label-enable`, a 24-hour interval, and `--cleanup`. Cleanup removes superseded images after an update; it must never remove Docker volumes or database files. - Apply `pull_policy: always` to published Docker images in deployment Compose files so a manual `docker compose up` checks the registry. Leave local development-only images alone and keep the updater itself version-pinned. - The Docker socket mount grants Watchtower broad control of the host. Document this risk and the lack of staged rollout/rollback; do not describe automatic updates as a production-safe rollback system. +- For each published Ubuntu-based Central, CPU Agent, or CUDA Agent runtime image, update the base OS package index, upgrade installed OS packages noninteractively, install runtime packages, and clear apt lists in one layer. Verify the final image with the repository's pinned Trivy scanner at HIGH/CRITICAL severity; a passing application build does not clear OS package advisories. ## Re-running the installer @@ -37,4 +38,6 @@ Use this skill when changing the Linux or Windows Central installer, its generat Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data. +When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance. + If acceptance builds a local Central/helper image, record its project-unique tag before build and remove/verify that exact tag in the same cleanup trap, including on failure. Do not remove registry/base images or use `--rmi all` or broad image pruning; Watchtower's deployment `--cleanup` behavior is separate from disposable-test cleanup. diff --git a/skills/site-ntfy-creation/SKILL.md b/skills/site-ntfy-creation/SKILL.md new file mode 100644 index 0000000..994d91a --- /dev/null +++ b/skills/site-ntfy-creation/SKILL.md @@ -0,0 +1,14 @@ +--- +name: site-ntfy-creation +description: Maintain and accept the site-specific ntfy topic through Heimdall site creation. +--- + +# Site ntfy creation + +The site topic is an optional destination used by notification delivery. Creation crosses a JSON DTO, `SitesController`, `CreateSiteCommand`, `CreateSiteHandler`, and `Site`; every layer must carry `NtfyTopic`. Keep the optional DTO parameter last/defaulted to preserve existing clients. The Sites page already sends it in `CreateSiteAsync`. + +## Acceptance + +1. Extend the PostgreSQL API integration test to POST a unique site name and `ntfyTopic`, then GET that site and assert `SiteResponse.NtfyTopic` equals the submitted topic. This catches JSON binding, controller mapping, and relational persistence together. +2. Run the focused integration test against the repository PostgreSQL fixture. +3. Follow `skills/compose-disposable-recipe/SKILL.md` to run a source-built disposable Compose stack. Bootstrap an isolated admin, create a site with a topic through `POST /api/sites`, read it back, and verify the topic. Remove the exact project and locally built tags and verify no project containers, volumes, or networks remain. diff --git a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs index 8ed54ab..9bd6d07 100644 --- a/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs +++ b/src/Heimdall.Agent/Services/AnalysisJobPollingService.cs @@ -137,7 +137,7 @@ public sealed class AnalysisJobPollingService : BackgroundService .ToArray()); } - private async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId, + internal async Task SendResultAsync(HttpClient client, Guid agentId, Guid jobId, AnalysisResult result, CancellationToken ct) { var retryDelay = TimeSpan.FromSeconds(2); @@ -155,6 +155,13 @@ public sealed class AnalysisJobPollingService : BackgroundService jobId, result.AttemptId); return; } + if ((int)response.StatusCode is >= 400 and < 500) + { + _logger.LogError( + "Analysis result for job {JobId} was permanently rejected with HTTP {StatusCode}; stopping retries", + jobId, (int)response.StatusCode); + return; + } _logger.LogWarning("Analysis result for job {JobId} was rejected with HTTP {StatusCode}; retrying", jobId, (int)response.StatusCode); } @@ -226,8 +233,8 @@ public sealed class AnalysisJobPollingService : BackgroundService private sealed record LeasedJob(Guid JobId, Guid CameraId, Guid AttemptId, JsonElement JobType, string? ParametersJson); - private sealed record AnalysisDetection(string Label, float Confidence, float X, float Y, + internal sealed record AnalysisDetection(string Label, float Confidence, float X, float Y, float Width, float Height, int? ClassIndex); - private sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error, + internal sealed record AnalysisResult(Guid AttemptId, bool Success, string? Error, IReadOnlyList Detections); } diff --git a/src/Heimdall.Agent/Services/LogUploadService.cs b/src/Heimdall.Agent/Services/LogUploadService.cs index 14b5394..55a98a0 100644 --- a/src/Heimdall.Agent/Services/LogUploadService.cs +++ b/src/Heimdall.Agent/Services/LogUploadService.cs @@ -16,6 +16,17 @@ namespace Heimdall.Agent.Services; /// public class LogUploadService : BackgroundService { + internal static string ToCentralLevel(LogLevel level) => level switch + { + LogLevel.Trace => "Trace", + LogLevel.Debug => "Debug", + LogLevel.Information => "Information", + LogLevel.Warning => "Warning", + LogLevel.Error => "Error", + LogLevel.Critical => "Critical", + _ => "Info" + }; + private readonly IHttpClientFactory _httpClientFactory; private readonly LogBufferService _buffer; private readonly AgentState _state; @@ -73,7 +84,7 @@ public class LogUploadService : BackgroundService entries = entries.Select(e => new { timestampUtc = e.TimestampUtc, - level = e.Level.ToString(), + level = ToCentralLevel(e.Level), message = e.Message, exception = e.Exception, source = e.Source diff --git a/src/Heimdall.Application/DTOs/SiteDto.cs b/src/Heimdall.Application/DTOs/SiteDto.cs index a706ba6..e04c6c4 100644 --- a/src/Heimdall.Application/DTOs/SiteDto.cs +++ b/src/Heimdall.Application/DTOs/SiteDto.cs @@ -1,6 +1,6 @@ namespace Heimdall.Application.DTOs; -public record CreateSiteRequest(string Name, string? Address, string? Timezone); +public record CreateSiteRequest(string Name, string? Address, string? Timezone, string? NtfyTopic = null); public record UpdateSiteRequest(string Name, string? Address, string? Timezone, string? NtfyTopic = null, bool? AutoUpdateEnabled = null); diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs index 7e734c2..05a4571 100644 --- a/src/Heimdall.Web/Controllers/AgentsController.cs +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -209,7 +209,7 @@ public class AgentsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task GetLogs( Guid id, - AgentLogsQuery query, + [FromQuery] AgentLogsQuery query, CancellationToken ct) { var result = await _mediator.Send( diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index f9fc219..ffa1fc5 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -49,7 +49,7 @@ public class SitesController : ControllerBase if (!this.TryGetUserId(out var actorId)) return Unauthorized(new { error = "Invalid user identity" }); - var command = new CreateSiteCommand(request.Name, request.Address, request.Timezone, ActorId: actorId); + var command = new CreateSiteCommand(request.Name, request.Address, request.Timezone, request.NtfyTopic, ActorId: actorId); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index feb0bc7..b7b0df0 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -15,6 +15,7 @@ + + { + requests++; + return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); + })) { BaseAddress = new Uri("http://localhost/") }; + var service = new AnalysisJobPollingService(null!, null!, null!, null!, null!, + NullLogger.Instance); + + await service.SendResultAsync(client, Guid.NewGuid(), Guid.NewGuid(), + new AnalysisJobPollingService.AnalysisResult(Guid.NewGuid(), true, null, []), + CancellationToken.None); + + requests.ShouldBe(1); + } + [Theory] [InlineData("\"PersonDetection\"", true)] [InlineData("\"vehicLeClassification\"", true)] @@ -54,4 +86,12 @@ public sealed class AnalysisJobPollingServiceTests actual.ShouldBe(expected); } + + private sealed class StubHttpMessageHandler( + Func responseFactory) : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + => Task.FromResult(responseFactory(request)); + } } diff --git a/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs b/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs index d2da723..f734960 100644 --- a/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs @@ -1,4 +1,6 @@ using Heimdall.Agent.Logging; +using Heimdall.Agent.Services; +using Heimdall.Domain.Enums; using Microsoft.Extensions.Logging; using Shouldly; @@ -6,6 +8,21 @@ namespace Heimdall.Agent.Tests; public class LogBufferServiceTests { + [Theory] + [InlineData(LogLevel.Trace, "Trace")] + [InlineData(LogLevel.Debug, "Debug")] + [InlineData(LogLevel.Information, "Information")] + [InlineData(LogLevel.Warning, "Warning")] + [InlineData(LogLevel.Error, "Error")] + [InlineData(LogLevel.Critical, "Critical")] + public void ToCentralLevel_MapsMicrosoftNamesToAgentContract(LogLevel level, string expected) + { + var centralName = LogUploadService.ToCentralLevel(level); + centralName.ShouldBe(expected); + Enum.TryParse(centralName, true, out var parsed).ShouldBeTrue(); + parsed.ShouldBe((AgentLogLevel)level); + } + private static BufferedLogEntry Entry(string message, LogLevel level = LogLevel.Information) => new(DateTime.UtcNow, level, message, null, "TestService"); diff --git a/tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs new file mode 100644 index 0000000..3a62b20 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/AgentLogsControllerTests.cs @@ -0,0 +1,45 @@ +using System.Net.Http.Json; +using Heimdall.Application.DTOs; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public sealed class AgentLogsControllerTests(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres) +{ + [Fact] + public async Task SubmitAgentLogs_CentralLevelNames_ArePersistedAndQueryable() + { + var admin = await Factory.CreateAdminClientAsync(); + var siteResponse = await admin.PostAsJsonAsync("api/sites", + new CreateSiteRequest("Agent log acceptance", null, "UTC")); + siteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var site = await siteResponse.Content.ReadFromJsonAsync(); + site.ShouldNotBeNull(); + site.RegistrationToken.ShouldNotBeNullOrWhiteSpace(); + + var agentClient = Factory.CreateClient(); + var registerResponse = await agentClient.PostAsJsonAsync("api/agents/register", + new RegisterAgentRequest(site.RegistrationToken!, "log-acceptance", "test", null)); + registerResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var agent = await registerResponse.Content.ReadFromJsonAsync(); + agent.ShouldNotBeNull(); + agent.ApiKey.ShouldNotBeNullOrWhiteSpace(); + agentClient.DefaultRequestHeaders.Add("X-API-Key", agent.ApiKey); + + var timestamp = DateTime.UtcNow; + var levels = new[] { "Trace", "Debug", "Information", "Warning", "Error", "Critical", "Info", "Warn" }; + var submitResponse = await agentClient.PostAsJsonAsync($"api/agents/{agent.AgentId}/logs", + new SubmitAgentLogsRequest(levels.Select(level => new AgentLogEntryRequest( + timestamp, level, "Synthetic PR138 log", null, "acceptance")).ToArray())); + submitResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var readResponse = await admin.GetAsync($"api/agents/{agent.AgentId}/logs?page=1&pageSize=50"); + readResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var logs = await readResponse.Content.ReadFromJsonAsync>(); + logs.ShouldNotBeNull(); + logs.TotalCount.ShouldBe(6); + logs.Items.Select(log => log.Level).Order(StringComparer.Ordinal) + .ShouldBe(new[] { "Critical", "Debug", "Error", "Information", "Trace", "Warning" }); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs index 6628ed3..4daf290 100644 --- a/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs +++ b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs @@ -24,11 +24,18 @@ public class SitesControllerTests : PostgresTestBase { name = "Site Test", address = "Paris", - timezone = "Europe/Paris" + timezone = "Europe/Paris", + ntfyTopic = "site-test-topic" }); - var body = await response.Content.ReadAsStringAsync(); - await File.WriteAllTextAsync("/tmp/test-response-body.txt", body); response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var created = await response.Content.ReadFromJsonAsync(); + created.ShouldNotBeNull(); + + var siteResponse = await client.GetAsync($"api/sites/{created.Id}"); + siteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + var site = await siteResponse.Content.ReadFromJsonAsync(); + site.ShouldNotBeNull(); + site.NtfyTopic.ShouldBe("site-test-topic"); } [Fact] diff --git a/todo.md b/todo.md index f29d4cc..1279f10 100644 --- a/todo.md +++ b/todo.md @@ -18,6 +18,12 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant ## P1 — parcours caméra, agent et données +- [ ] **AGENT-INSTALL-ASSETS** Central renvoyait HTTP 404 pour `/install/agent-supervisor.py`, car le middleware statique ASP.NET Core n'associait aucun type MIME à `.py` et refusait le fichier pourtant présent dans le publish. `Program.ConfigureMiddleware` mappe maintenant `.py` vers `text/x-python`. Deux recettes source Compose ont confirmé `/healthz` sain et les deux assets HTTP 200 identiques à la source; la recette `hmd-pr138-verified-1793916772-972` vérifie aussi `text/x-python`. Projet final nettoyé 0/0/0 et image `heimdall:hmd-pr138-verified-1793916772-972-central` absente. Le Central public répondait encore 404 au contrôle initial; le déploiement/restart et la vérification publique restent à faire. Skill : `skills/agent-update-acceptance/SKILL.md`. + +- [x] **Contrats Agent / création de site** L'upload des logs envoie maintenant les noms d'énumération acceptés par Central (`Information`, `Warning`); une réponse 4xx à un résultat d'analyse est définitive et libère la boucle de polling. La création de site propage le sujet ntfy optionnel au handler. La recette source Compose a révélé puis corrigé le 415 de `GET /api/agents/{id}/logs` en liant son filtre depuis la query string. Tests Agent ciblés 25/25; intégration PostgreSQL source Compose 2/2 (création site/topic, ajout de logs, rejet des alias `Info`/`Warn`, lecture des six sévérités) et build Web sans avertissement. Projet `hmd-pr138-verified-1793916772-972` teardown 0/0/0, image exacte absente. Skills : `skills/agent-runtime-acceptance/SKILL.md`, `skills/analysis-job-pipeline/SKILL.md`, `skills/site-ntfy-creation/SKILL.md`. + +- [ ] **SECURITY/IMAGE-APT-UPDATE** Le run CI PR #756 a réussi les builds serveur/Agent/CUDA mais les trois scans Trivy et `CI policy` ont échoué. Le scan local du Central source a isolé `CVE-2026-109518` dans `apt` et `libapt-pkg6.0t64` 2.8.3 (correctif Ubuntu 2.8.4ubuntu0.1). Les trois Dockerfiles runtime mettent maintenant à niveau les paquets OS avant l'installation des dépendances. Tentative de recette Central source avec le tag isolé `heimdall:hmd-pr138-apt-1793946707-574639-central`: l'upgrade APT est resté bloqué en état noyau `D` pendant plus d'une minute; interruption de la tentative, projet vérifié sans conteneur/volume/réseau et tag absent. Le scan post-correctif n'est donc pas validé localement. La CI doit valider les builds et scans Trivy HIGH/CRITICAL des trois images; aucune publication ne doit être déclarée tant que ce run n'a pas réussi. Skill : `skills/central-auto-updates/SKILL.md`. + - [x] Corriger la fixture unitaire `CreateEventHandlerTests` révélée rouge par la CI de la PR #138 : elle ne configurait pas `Recordings`, requis par la requête EF du handler. Le test initialise maintenant un `MockDbSet` vide. Le run #753 a aussi révélé que la bannière PWA du contexte loopback interceptait les dialogues Playwright; la fixture E2E la ferme après navigation. Ces précautions sont documentées dans `skills/analysis-job-pipeline/SKILL.md`; la CI PR reste à relancer pour confirmer l’ensemble des suites. - [x] **AUTH-BOOTSTRAP** L’assistant `/setup` ne crée le premier compte que sur une base vide et lui attribue Admin dans une transaction PostgreSQL sérialisable; l’UI login redirige vers l’assistant au premier lancement. L’inscription anonyme et l’ancienne route `register-admin` renvoient 404; les comptes suivants passent par l’UI `/users` et l’API protégée `Admin.Users`. Recette Compose jetable finale du 4 novembre 2026 : statut initial ouvert → premier Admin → statut fermé → création d’utilisateurs protégée; vérification de la route setup, refus anonyme et suppression des deux anciennes routes. Tests PostgreSQL intégration complets 161/161; tests E2E AuthFlow/UI utilisateur réussis (résultats notés dans USER-RBAC ci-dessous). Le bootstrap concurrent reste couvert par les tests PostgreSQL dédiés. -- 2.54.1