Compare commits
31
Commits
1.0.6
...
f5029a4424
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5029a4424 | ||
|
|
04b3279d1f | ||
|
|
0cc41235c7 | ||
|
|
32d68595d5 | ||
|
|
8df487002e | ||
|
|
f1894a26d6 | ||
|
|
d1dcd903d7 | ||
|
|
068dd44304 | ||
|
|
91816fbf29 | ||
|
|
4898d8343d | ||
|
|
b78c3deea2 | ||
|
|
bf13b70a53 | ||
|
|
b4d24c3345 | ||
|
|
8f3d75680d | ||
|
|
1e84000749 | ||
|
|
02cd37a1cb | ||
|
|
e2a73431b5 | ||
|
|
333036aa36 | ||
|
|
53bb5e8b06 | ||
|
|
79b4b86177 | ||
|
|
c065b44578 | ||
|
|
021bdecab3 | ||
|
|
f20ec93f6f | ||
|
|
1a570a31e3 | ||
|
|
cd8536ac65 | ||
|
|
f18df60b42 | ||
|
|
af7a1b9585 | ||
|
|
bdffcf4732 | ||
|
|
96d53b201f | ||
|
|
561feb424c | ||
|
|
72edf1c514 |
No files matched your search
@@ -2,13 +2,14 @@
|
||||
name: "🐛 Bug"
|
||||
about: "Comportement incorrect, régression ou risque fonctionnel détecté"
|
||||
title: "BUG: "
|
||||
labels: ["bug"]
|
||||
labels: ["type:bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Bug — à remplir avant de commencer
|
||||
> Si le bug est un écart par rapport à la spec, citer `docs/MASTER_SPECIFICATION.md`.
|
||||
> Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés. Voir `skills/gitea-ticket-workflow/SKILL.md`.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -22,7 +23,7 @@ body:
|
||||
id: observe
|
||||
attributes:
|
||||
label: "🐞 Comportement observé"
|
||||
description: "Ce qui se passe réellement (avec logs/erreurs si dispo)"
|
||||
description: "Ce qui se passe réellement (avec logs/erreurs expurgés de toute donnée sensible)"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -38,7 +39,7 @@ body:
|
||||
id: repro
|
||||
attributes:
|
||||
label: "🔁 Reproduction"
|
||||
description: "Étapes pour reproduire + environnement (dev/prod, docker, env vars)"
|
||||
description: "Étapes pour reproduire + environnement (dev/prod, Docker, noms de variables sans leurs valeurs)"
|
||||
placeholder: "1. …\n2. …\n3. …"
|
||||
|
||||
- type: input
|
||||
@@ -69,5 +70,4 @@ body:
|
||||
options:
|
||||
- label: "Bug reproduit avant fix (test qui échoue)"
|
||||
- label: "Fix implémenté + tests verts (`make test`)"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
@@ -2,12 +2,13 @@
|
||||
name: "🔧 Maintenance / Chore"
|
||||
about: "Tâche de maintenance, mise à jour de dépendance, CI, outillage"
|
||||
title: "CHORE: "
|
||||
labels: ["chore"]
|
||||
labels: ["type:maintenance"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Maintenance / Chore
|
||||
Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés. Voir `skills/gitea-ticket-workflow/SKILL.md`.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -44,4 +45,4 @@ body:
|
||||
label: "✅ Definition of Done"
|
||||
options:
|
||||
- label: "Tâche réalisée + vérifiée"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
@@ -2,13 +2,14 @@
|
||||
name: "✨ Feature"
|
||||
about: "Nouvelle fonctionnalité ou implémentation manquante par rapport à la spécification"
|
||||
title: "FEAT: "
|
||||
labels: ["feature"]
|
||||
labels: ["type:feature"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Feature — à remplir avant de commencer
|
||||
> Source de vérité : `docs/MASTER_SPECIFICATION.md` (v2.0). Citer les numéros de partie/phase/étape.
|
||||
> Avant de commencer, ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés. Voir `skills/gitea-ticket-workflow/SKILL.md`.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -75,5 +76,4 @@ body:
|
||||
- label: "Code implémenté + tests verts (`make test`)"
|
||||
- label: "Migration EF ajoutée si le schéma change"
|
||||
- label: "Documentation/readme mis à jour si pertinent"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
@@ -2,12 +2,13 @@
|
||||
name: "🧹 Dette technique"
|
||||
about: "Dette technique, obsolescence, drift documentation, amélioration de code"
|
||||
title: "TECH: "
|
||||
labels: ["tech-debt"]
|
||||
labels: ["type:maintenance"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Dette technique — à remplir avant de commencer
|
||||
Ajouter les labels `priority:P0`…`priority:P3` et `area:*` adaptés. Voir `skills/gitea-ticket-workflow/SKILL.md`.
|
||||
|
||||
- type: textarea
|
||||
id: contexte
|
||||
@@ -53,5 +54,4 @@ body:
|
||||
label: "✅ Definition of Done"
|
||||
options:
|
||||
- label: "Correctif appliqué + vérifié"
|
||||
- label: "Statut du ticket mis à jour (via skill forgejo-issues)"
|
||||
- label: "Carte kanban Hermes mise à jour (lien vers l'issue)"
|
||||
- label: "Issue et preuves mis à jour dans Gitea selon le workflow commun"
|
||||
@@ -1,25 +1,31 @@
|
||||
## Problème et résultat
|
||||
## Résultat et périmètre
|
||||
|
||||
<!-- Décrire le déclencheur, le comportement corrigé et le périmètre. -->
|
||||
<!-- Décrire le besoin, le résultat et les critères de l'issue couverts par cette PR. -->
|
||||
|
||||
Refs #
|
||||
|
||||
## Vérification
|
||||
|
||||
<!-- Issue Gitea liée, liens des runs Gitea, suites exécutées et résultats observés. -->
|
||||
<!-- Commandes, preuves observées, limites et SHA du commit vérifié. Pour un diff Markdown-only, noter les contrôles de diff/liens; ne pas lancer de build ou de stack applicative sans raison. -->
|
||||
|
||||
- [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images
|
||||
- [ ] Contrôles NuGet et images sans HIGH/CRITICAL
|
||||
- [ ] Limites et tests non exécutés explicitement documentés
|
||||
- [ ] Aucun secret dans les logs/artefacts
|
||||
- [ ] Issue Gitea liée et critères satisfaits/restants précisés
|
||||
- [ ] Contrôles pertinents exécutés; commandes et résultats indiqués
|
||||
- [ ] Recette Compose indépendante indiquée lorsqu'elle est requise, avec preuves de nettoyage
|
||||
- [ ] Limites et validations externes non réalisées explicitement documentées
|
||||
- [ ] Aucun secret dans le diff, les logs ou les artefacts
|
||||
|
||||
## Livraison
|
||||
## Évaluation de release
|
||||
|
||||
<!-- Voir docs/gitea-builds.md. Pas de merge/déploiement implicite. -->
|
||||
<!-- Suivre skills/pr-release-versioning/SKILL.md et /home/nonobis/skills/skills/release-assessment/SKILL.md. -->
|
||||
|
||||
- [ ] Traçabilité commit → résultats → SHA256 des archives → digests images
|
||||
- [ ] Revue des changements de contrats/migrations/configuration
|
||||
- [ ] Si la PR change un graphe d’image : seules les images affectées ont été construites/scannées; publication Docker Hub vérifiée après merge
|
||||
- [ ] Si elle change la livraison : le workflow de tag versionné et la release Gitea versionnée sont documentés et acceptés
|
||||
Release: no — raison
|
||||
|
||||
SonarQube, matériel et autres contrôles externes ne sont considérés validés que si une preuve réelle est jointe. Une protection de branche doit exiger le contexte Gitea constaté sur le run avant de compter sur le blocage d’un merge.
|
||||
## Livraison Heimdall
|
||||
|
||||
<!-- Voir docs/gitea-builds.md si la PR touche CI, publication ou assets de release. -->
|
||||
|
||||
- [ ] Compatibilité contrats/migrations/configuration revue si concernée
|
||||
- [ ] Si le graphe d'image change : images affectées construites/scannées; publication Docker Hub observée après merge
|
||||
- [ ] Si les assets changent : noms, SHA-256/signature et format de release documentés; aucun claim externe sans run réel
|
||||
|
||||
SonarQube, runner, matériel, registre, site et stockage distant ne sont considérés validés que si une preuve réelle est jointe. Aucun merge ou déploiement n'est implicite.
|
||||
@@ -1,18 +1,29 @@
|
||||
# Heimdall contributor rules
|
||||
# Règles Heimdall
|
||||
|
||||
- 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, 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.
|
||||
- Use Gitea project issues as the sole backlog and work-status source. Before changing code, find or create the focused issue, keep its acceptance evidence current, and link the issue from the PR (`Closes #N` only when all criteria are complete; otherwise `Refs #N`). Follow [skills/gitea-ticket-workflow/SKILL.md](skills/gitea-ticket-workflow/SKILL.md). Do not create or maintain a `todo.md` backlog.
|
||||
- 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.
|
||||
- Use EF Core for production database reads and writes. Do not use direct ADO.NET or provider commands in production code; provider-specific EF SQL is allowed only for capabilities LINQ cannot express, with a nearby rationale and a test. The CI persistence policy enforces this boundary. Preserve PostgreSQL behavior, add migrations for schema changes, and verify translation, concurrency, and deletion semantics with relational tests. Never reuse a `DbContext` across concurrent operations.
|
||||
- Keep tenant/site and camera authorization checks at API and application boundaries. Do not log credentials, RTSP URLs, embeddings, or raw tokens.
|
||||
- CI jobs run only on `[ubuntu-latest, build-agent]`. Keep `runner-aaja` outside that label. Never use release credentials in pull request jobs.
|
||||
- A PR touching deployment or publication must document required secrets and prove the relevant script locally. Do not claim a runner, registry, camera, or object store was validated without a real run.
|
||||
Les pratiques génériques sont définies dans les skills communs sous `/home/nonobis/skills/skills/`. Les appliquer sans les recopier ici :
|
||||
|
||||
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
|
||||
For Penpot design work, follow [skills/penpot-design-sync/SKILL.md](skills/penpot-design-sync/SKILL.md): always open Penpot and establish the authenticated session through the Orca browser, and keep the connected design synchronized with relevant shipped UI changes.
|
||||
When work can be split safely, follow [skills/parallel-development/SKILL.md](skills/parallel-development/SKILL.md) to dispatch independent investigations and implementation through Orca, then integrate and validate the combined change once.
|
||||
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
|
||||
For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md).
|
||||
For Central installer, Compose, or server image update changes, also use [skills/central-auto-updates/SKILL.md](skills/central-auto-updates/SKILL.md).
|
||||
- cycle Gitea unique : [gitea-delivery-workflow](/home/nonobis/skills/skills/gitea-delivery-workflow/SKILL.md), avec l'authentification, les labels et champs Heimdall précisés dans [gitea-ticket-workflow](skills/gitea-ticket-workflow/SKILL.md) ;
|
||||
- pratiques .NET/EF Core : [dotnet-engineering](/home/nonobis/skills/skills/dotnet-engineering/SKILL.md) ; profil réel des projets Heimdall dans [heimdall-dotnet](skills/heimdall-dotnet/SKILL.md) ;
|
||||
- CI, runners, conteneurs et publication : [devops-engineering](/home/nonobis/skills/skills/devops-engineering/SKILL.md) ; profil CI et release Heimdall dans les skills locales correspondantes ;
|
||||
- coordination Orca : [orca-parallel-work](/home/nonobis/skills/skills/orca-parallel-work/SKILL.md) ; frontières et critères Heimdall dans [parallel-development](skills/parallel-development/SKILL.md) ;
|
||||
- environnements jetables : [disposable-test-environment](/home/nonobis/skills/skills/disposable-test-environment/SKILL.md), complété par la recette exacte [Compose Heimdall](skills/compose-disposable-recipe/SKILL.md) ;
|
||||
- identité, Infisical et MCP : [secure-identity-lifecycle](/home/nonobis/skills/skills/secure-identity-lifecycle/SKILL.md), [infisical-cli](/home/nonobis/skills/skills/infisical-cli/SKILL.md) et [mcp-configuration](/home/nonobis/skills/skills/mcp-configuration/SKILL.md), complétés par les profils locaux sans inventaire de secrets.
|
||||
|
||||
## Contraintes Heimdall
|
||||
|
||||
- Pour toute fonctionnalité, correction, opération ou documentation significative, créer ou mettre à jour une skill ciblée sous `skills/` dans la même PR. Elle décrit le contexte et l'acceptation propres à Heimdall.
|
||||
- Les issues Gitea sont l'unique backlog. Avant une modification, chercher ou créer l'issue et tenir ses critères et preuves à jour. Lier la PR avec `Closes #N` seulement si tous les critères sont remplis; sinon utiliser `Refs #N`. Ne pas maintenir de `todo.md`.
|
||||
- L'architecture réelle est portée par `Heimdall.Domain` et `Heimdall.Domain.Primitives`, `Heimdall.Application`, `Heimdall.Infrastructure`, `Heimdall.Web` et `Heimdall.Agent`; `Heimdall.Contracts` et `Heimdall.Mdns` sont des projets séparés. Domain reste indépendant; Application porte cas d'usage et ports; Infrastructure porte adaptateurs/persistance; Web compose HTTP/UI; Agent porte caméra et runtime.
|
||||
- Cibler le SDK défini dans `global.json` (actuellement 10.0.100) et les projets .NET 10+. Préserver les fournisseurs Central PostgreSQL et Agent SQLite ainsi que leur compatibilité de schéma respective.
|
||||
- Central utilise EF Core en production. La règle CI `scripts/ci/check-efcore-usage.py` interdit les commandes ADO.NET/fournisseur directes en production; maintenir sa liste d'exceptions étroite, motivée et testée. Toute évolution de schéma Central a une migration EF Core révisée. Conserver la procédure d'identité de migration et de vérification/checksum définie dans les skills spécialisées.
|
||||
- Pour les changements de comportement ou de déploiement, exécuter la recette Compose jetable construite depuis le code modifié. Générer secrets, ports, volumes, réseaux, nom de projet et tags locaux uniques; installer le trap avant build/start; supprimer uniquement les ressources de ce projet et vérifier leur absence. Garder les images upstream partagées et ne jamais lancer de prune global.
|
||||
- Les jobs CI utilisent seulement les labels `[ubuntu-latest, build-agent]`; garder `runner-aaja` hors de ces labels. Aucun secret de publication dans les jobs PR.
|
||||
- Les changements de publication ou déploiement documentent les secrets requis par nom et prouvent localement le script concerné. Ne pas affirmer qu'un runner, registre, appareil ou stockage distant a été validé sans exécution réelle.
|
||||
- Les contrôles d'accès site/caméra restent appliqués aux frontières API et Application. Ne jamais journaliser credentials, URL RTSP, embeddings ou tokens bruts.
|
||||
|
||||
## Skills de contexte et d'acceptation
|
||||
|
||||
- Penpot : [penpot-design-sync](skills/penpot-design-sync/SKILL.md) ; ouvrir Penpot via le navigateur Orca et maintenir le design connecté aligné aux changements UI livrés.
|
||||
- Bootstrap administrateur : [first-admin-bootstrap](skills/first-admin-bootstrap/SKILL.md).
|
||||
- Central installer, Compose et images serveur : [central-auto-updates](skills/central-auto-updates/SKILL.md).
|
||||
- Persistance EF Core et migration de démarrage : [ef-core-persistence](skills/ef-core-persistence/SKILL.md) et [database-migration-startup](skills/database-migration-startup/SKILL.md).
|
||||
+15
-4
@@ -6,11 +6,17 @@ Sauvegarde automatisée de PostgreSQL (quotidien) et RustFS/S3 (hebdomadaire) av
|
||||
|
||||
| Composant | Fréquence | Script | Rétention |
|
||||
|---|---|---|---|
|
||||
| PostgreSQL `pg_dump` | Quotidien 02:00 UTC | `docker/scripts/backup.sh` | 30 jours (local) + 30 jours (S3) |
|
||||
| RustFS `mc mirror` | Hebdo dimanche 03:00 UTC | `docker/scripts/backup-rustfs.sh` | 12 semaines |
|
||||
| Volume Central (objets locaux + clés Data Protection) | Quotidien 02:15 UTC | `docker/scripts/backup-protected-data.sh` | 30 jours (local); cycle S3 selon la politique de bucket |
|
||||
| PostgreSQL `pg_dump` | Quotidien 02:00, heure du conteneur | `docker/scripts/backup.sh` | 30 jours (local) + 30 jours (S3) |
|
||||
| Miroir RustFS/S3 (`aws s3 sync` dans le Compose livré) | Dimanche 03:00, heure du conteneur | `docker/scripts/backup-rustfs.sh` | 12 semaines |
|
||||
| Volume Central (objets locaux + clés Data Protection) | Quotidien 02:15, heure du conteneur | `docker/scripts/backup-protected-data.sh` | 30 jours (local); cycle S3 selon la politique de bucket |
|
||||
| Test de restauration | Manuel / CI | `docker/scripts/test-backup-restore.sh` | — |
|
||||
|
||||
Le Compose backup définit `TZ` à `Europe/Paris` par défaut; ces horaires
|
||||
s'appliquent donc à l'heure locale de Paris, avec les changements saisonniers.
|
||||
Définir `TZ` avec un identifiant de fuseau IANA pour choisir un autre fuseau.
|
||||
Les scripts horodatent leurs archives en UTC; l'heure du nom d'archive peut donc
|
||||
différer de l'heure locale d'exécution.
|
||||
|
||||
## Activation
|
||||
|
||||
### Compose facultatif séparé
|
||||
@@ -25,6 +31,10 @@ rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine
|
||||
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 fourni installe AWS CLI, pas MinIO Client : `backup-rustfs.sh`
|
||||
utilise donc `aws s3 sync` avec l'endpoint configuré. Le script conserve un
|
||||
chemin de compatibilité `mc mirror` si `mc` est déjà présent dans une image ou
|
||||
un environnement personnalisé; il ne télécharge ni n'installe ce binaire.
|
||||
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.
|
||||
Le nom par défaut est `docker_heimdall_data`, pour le projet Compose du dépôt.
|
||||
@@ -50,6 +60,7 @@ configurés. Garder l’application Central arrêtée pendant une restauration.
|
||||
| `BACKUP_RETENTION_DAYS` | `30` | Rétention jours (PostgreSQL) |
|
||||
| `BACKUP_RETENTION_WEEKS` | `12` | Rétention semaines (RustFS) |
|
||||
| `BACKUP_LOCAL_DIR` | `/backups` | Répertoire local dans le conteneur |
|
||||
| `TZ` | `Europe/Paris` | Fuseau utilisé par le planning cron du conteneur |
|
||||
|
||||
## Structure des backups
|
||||
|
||||
@@ -321,6 +332,6 @@ docker compose -f docker/docker-compose.backup.yml exec backup ls -la /var/log/b
|
||||
|
||||
- **pg_dump --format=custom** nécessite `pg_restore` pour la restauration (pas `psql`)
|
||||
- Le conteneur backup utilise `postgres:17-alpine` pour avoir `pg_dump` et `pg_restore`
|
||||
- mc (MinIO Client) est installé au démarrage du conteneur (curl depuis dl.min.io)
|
||||
- Le Compose livré installe `aws-cli`, Bash et GNU coreutils; il n'installe pas MinIO Client. Le script de miroir préfère `mc` s'il est déjà fourni, sinon utilise AWS CLI `s3 sync`.
|
||||
- Si S3 n'est pas configuré, le backup est local uniquement (volume Docker)
|
||||
- La restauration DROP la base existante — toujours vérifier le `--dry-run` d'abord
|
||||
@@ -1,4 +1,6 @@
|
||||
# Optional TURN relay, used only by a future/externally integrated WebRTC setup.
|
||||
# Optional TURN relay for live view; Central uses its URL and shared secret to
|
||||
# issue short-lived browser credentials. Public reachability needs deployment
|
||||
# firewall/NAT validation.
|
||||
services:
|
||||
coturn:
|
||||
image: coturn/coturn:4.6
|
||||
|
||||
+137
-134
@@ -1,8 +1,9 @@
|
||||
# Heimdall — Master Specification Technique
|
||||
|
||||
> **Version :** 2.0 | **Date :** 2026-07-16
|
||||
> **Stack :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents) / SIPSorcery / WebRTC
|
||||
> **Status :** SPECIFICATION FINALE — synthèse de 5600+ lignes de docs, revue par 5 agents experts
|
||||
> **Stack de la baseline :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents)
|
||||
> **Statut :** baseline de conception historique datée du 2026-07-16; ce document n'est pas la source de vérité sur l'implémentation livrée.
|
||||
> **État livré :** voir [spécifications actuelles](specs.md), [hubs SignalR mappés](signalr-usage.md), [déploiement Compose et live view](docker-compose.md), et [skill live-view](../skills/webrtc-live/SKILL.md).
|
||||
>
|
||||
> **Documents sources fusionnés :** `specs.md`, `implementation.md`, `notifications.md`, `signalr-usage.md`,
|
||||
> `auth-roles.md`, `pwa.md`, `hangfire-usage.md`, `ui-pages.md`
|
||||
@@ -16,7 +17,7 @@
|
||||
|
||||
### D1 — Accès mobile via la PWA du serveur
|
||||
|
||||
Le client natif est retiré. L’application Blazor devient la cible mobile installable ; la première version conserve Interactive Server avec une page hors connexion et Web Push. La consultation métier hors ligne nécessitera une couche cliente autonome. Voir [l’audit PWA](pwa.md).
|
||||
Le client natif est retiré. L’application Blazor est la cible mobile installable. Le socle livré conserve Interactive Server et fournit une page statique hors connexion; Web Push et la consultation métier hors ligne restent des objectifs non implémentés. Voir [l’état livré et l’audit PWA](pwa.md).
|
||||
|
||||
### D2 — Topologie : API + Web fusionnés (1 conteneur)
|
||||
|
||||
@@ -27,29 +28,29 @@ Le client natif est retiré. L’application Blazor devient la cible mobile inst
|
||||
|
||||
**Exception** : En scaling horizontal, on peut séparer les conteneurs avec un Redis backplane.
|
||||
|
||||
### D3 — TURN/Coturn obligatoire (pas optionnel)
|
||||
### D3 — TURN selon la connectivité du réseau (ancienne décision obligatoire retirée)
|
||||
|
||||
| Choix | Raison |
|
||||
|---|---|
|
||||
| **Coturn REQUIS** | CGNAT (4G/5G), pare-feu entreprises, Starlink — toute installation derrière NAT |
|
||||
| Optionnel rejeté | WebRTC échoue silencieusement sans TURN → support impossible |
|
||||
| **TURN est une option de déploiement** | Les connexions ICE directes peuvent suffire; déployer et configurer TURN lorsque le NAT ou le pare-feu empêche la connectivité directe. |
|
||||
| Pas de TURN universellement requis | La présence du Compose Coturn ne prouve ni sa configuration Central, ni son accessibilité publique; ces vérifications restent propres au déploiement. |
|
||||
|
||||
### D4 — Agents : Installation Docker uniquement
|
||||
|
||||
| Choix | Raison |
|
||||
|---|---|
|
||||
| **Docker uniquement** | FFmpeg, SIPSorcery, YOLOv8 (ONNX Runtime) ont des dépendances natives complexes |
|
||||
| **Docker uniquement** | FFmpeg et ONNX Runtime ont des dépendances natives et des besoins de cycle de vie qu'il faut distribuer avec l'Agent |
|
||||
| Installation manuelle rejetée | Gestion des versions, dépendances système, mise à jour = cauchemar sans conteneurisation |
|
||||
|
||||
**Conséquence** : L'Agent est distribué exclusivement via `eltruncho/heimdall-agent` sur Docker Hub.
|
||||
Pas de binaire standalone, pas de .deb, pas d'installation manuelle. La mise à jour se fait par `docker pull` + redémarrage.
|
||||
|
||||
### D6 — SFU (MediaMTX) différé à v2
|
||||
### D6 — Chemin live-view livré : relay Agent vers MediaMTX, lecture WHEP/WebRTC
|
||||
|
||||
| Choix | Raison |
|
||||
|---|---|
|
||||
| **P2P uniquement en v1** (1 viewer/caméra max) | Complexité de transition P2P→SFU sous-estimée |
|
||||
| SFU repoussé à v2 | Renégociation SDP pendant flux actif = perte d'images, protocole non spécifié |
|
||||
| **L'Agent publie le flux RTSP(S) vers MediaMTX; le navigateur lit par WHEP/WebRTC** | Ce chemin est implémenté dans le relay Agent et l'API/session Central. Il ne repose pas sur une PeerConnection SIPSorcery dans l'Agent. |
|
||||
| La capacité et la connectivité restent à valider par environnement | Les limites de sessions, codecs, NAT/TURN et latence dépendent du déploiement; voir `docs/docker-compose.md` et l'issue #161 pour la validation externe. |
|
||||
|
||||
### D7 — CQRS avec MediatR in-process (pas de message broker)
|
||||
|
||||
@@ -73,6 +74,11 @@ Contrôleur → IMediator.Send(Command/Query) → [ValidationBehavior]
|
||||
|
||||
## PARTIE 1 : Architecture Globale
|
||||
|
||||
> **Schémas historiques (2026-07-16), non descriptifs du runtime actuel.** Les
|
||||
> schémas de conteneurs et les diagrammes détaillés ci-dessous gardent la
|
||||
> proposition d'origine; pour les composants livrés, suivre les liens d'état
|
||||
> courant dans l'en-tête.
|
||||
|
||||
### 1.1 Vision
|
||||
|
||||
Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, multi-site.
|
||||
@@ -85,11 +91,15 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu
|
||||
| **Privacy First** | IA ONNX Runtime en local sur les agents, 0 envoi de données au cloud |
|
||||
| **Multi-site** | 1 serveur Central + N Agents distants (sites physiques séparés) |
|
||||
| **Clean Architecture / CQRS** | Domain → Application → Infrastructure → Api/Web |
|
||||
| **Temps réel** | SignalR (5 hubs), WebRTC P2P < 500ms (LAN) |
|
||||
| **Temps réel** | SignalR (5 hubs mappés : Config, Events, Monitoring, Notifications, Admin); vidéo en direct : Agent RTSP(S) → MediaMTX → navigateur WHEP/WebRTC, sans seuil de latence revendiqué |
|
||||
| **IA locale** | YOLOv8 nano ONNX (Agent CPU) + GPU NVIDIA/AMD/Intel sur agents équipés, mutualisable inter-sites via broker |
|
||||
|
||||
### 1.3 Architecture Logique
|
||||
|
||||
> **Diagramme de conception historique (2026-07-16), pas le chemin vidéo livré.**
|
||||
> Il représente l'ancienne proposition SIPSorcery/P2P. Le chemin live actuel est
|
||||
> résumé en D6 et détaillé dans le [guide live-view](docker-compose.md).
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ HEIMDALL CENTRAL (1 container) │
|
||||
@@ -126,6 +136,10 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu
|
||||
|
||||
### 1.4 Conteneurs Docker
|
||||
|
||||
> **Exemple de topologie historique, non équivalent aux Compose actuels.**
|
||||
> Coturn n'est pas obligatoire pour chaque installation; voir
|
||||
> [les services Compose maintenus](docker-compose.md).
|
||||
|
||||
```yaml
|
||||
services:
|
||||
heimdall-central: # Api + Web + Workers fusionnés (1 conteneur)
|
||||
@@ -144,6 +158,11 @@ services:
|
||||
|
||||
### 2.1 Définitions
|
||||
|
||||
> **Schéma de conception historique (2026-07-16).** Les champs de
|
||||
> notification ci-dessous, dont `GotifyEnabled` et `NotificationTemplate`, ne
|
||||
> sont pas l’inventaire du modèle livré. Voir le [guide actuel des
|
||||
> notifications](notifications.md) et le [modèle d’identité courant](auth-roles.md).
|
||||
|
||||
```
|
||||
Site Agent Camera
|
||||
├── Id (Guid) PK ├── Id (Guid) PK ├── Id (Guid) PK
|
||||
@@ -288,12 +307,15 @@ CREATE INDEX idx_license_plate ON license_plates USING GIN
|
||||
|
||||
### 3.1 Problème : Objets Stationnaires
|
||||
|
||||
> **Estimation théorique historique**, pas une mesure ni une description des
|
||||
> canaux livrés.
|
||||
|
||||
**Sans dédoublonnage** : une personne immobile 10 minutes génère :
|
||||
- 3000 snapshots (200ms × 600s)
|
||||
- 3000 inférences YOLOv8 nano
|
||||
- 3000 analyses IA (ONNX local ou via broker)
|
||||
- 3000 événements en base
|
||||
- 3000 notifications (email + gotify + in-app)
|
||||
- 3000 notifications dans ce scénario théorique
|
||||
|
||||
**Solution** : Architecture de dédoublonnage à 4 niveaux.
|
||||
|
||||
@@ -440,6 +462,10 @@ public class CameraDetectionProfile
|
||||
|
||||
## PARTIE 4 : Authentification, Rôles et Sécurité
|
||||
|
||||
> **Conception historique.** Les exemples ci-dessous incluent un `StreamingHub`
|
||||
> proposé qui n'est pas mappé. Les hubs et routes actuels sont listés dans
|
||||
> [le guide SignalR](signalr-usage.md).
|
||||
|
||||
### 4.1 Architecture Auth
|
||||
|
||||
```
|
||||
@@ -571,7 +597,10 @@ Agent se connecte à SignalR avec API Key
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 5 : SignalR — 5 Hubs Détaillés
|
||||
## PARTIE 5 : Conception SignalR historique — 5 hubs projetés
|
||||
|
||||
> Cette proposition datée inclut `/hubs/streaming`, qui n'est pas livré. Voir
|
||||
> [les cinq routes actuellement mappées](signalr-usage.md).
|
||||
|
||||
### 5.1 Hubs
|
||||
|
||||
@@ -648,7 +677,12 @@ builder.Services.AddSignalR()
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 6 : WebRTC et Pipeline Vidéo
|
||||
## PARTIE 6 : Conception historique P2P/SIPSorcery — remplacée pour le live view
|
||||
|
||||
> Les sections ci-dessous conservent l'ancienne proposition P2P/SIPSorcery et
|
||||
> ses objectifs de latence, pas le comportement livré. Le chemin actuel est
|
||||
> Agent RTSP(S) → MediaMTX → navigateur WHEP/WebRTC; voir le
|
||||
> [guide Compose](docker-compose.md) et le [skill live-view](../skills/webrtc-live/SKILL.md).
|
||||
|
||||
### 6.1 Stack
|
||||
|
||||
@@ -815,6 +849,10 @@ await storageProvider.DeleteBatchAsync(storagePaths, ct);
|
||||
|
||||
### 7.4 Hangfire Configuration
|
||||
|
||||
> **Exemple de queues historique.** Les queues `email`/`gotify` du bloc
|
||||
> suivant ne décrivent pas les jobs actuels; voir le [guide Hangfire](hangfire-usage.md)
|
||||
> et le [guide des notifications livrées](notifications.md).
|
||||
|
||||
```csharp
|
||||
// Central — with schema isolation
|
||||
builder.Services.AddHangfire(config =>
|
||||
@@ -826,7 +864,7 @@ builder.Services.AddHangfire(config =>
|
||||
});
|
||||
});
|
||||
|
||||
// Queue isolation
|
||||
// Queue isolation (conception historique)
|
||||
[Queue("email")]
|
||||
public class SendNotificationEmailJob { ... }
|
||||
|
||||
@@ -846,6 +884,10 @@ builder.Services.AddHangfireServer(options =>
|
||||
|
||||
### 7.5 Jobs Hangfire — Tous
|
||||
|
||||
> **Inventaire historique (2026-07-16), pas la liste des jobs actuellement
|
||||
> enregistrés.** Consulter le [guide Hangfire actuel](hangfire-usage.md) pour
|
||||
> les jobs et queues livrés.
|
||||
|
||||
**Central (PostgreSQL)**
|
||||
|
||||
| Job | Schedule | Queue | Description |
|
||||
@@ -872,66 +914,19 @@ builder.Services.AddHangfireServer(options =>
|
||||
|
||||
## PARTIE 8 : Notifications
|
||||
|
||||
### 8.1 Canaux
|
||||
> **Conception historique non livrée.** Les canaux Gotify, l’éditeur de
|
||||
> templates Scriban et les événements de ces tableaux ne décrivent pas le
|
||||
> produit actuel. Pour les canaux, réglages et jobs livrés, voir
|
||||
> [Notifications](notifications.md).
|
||||
|
||||
| Canal | Usage | Priorité | Queue Hangfire |
|
||||
|---|---|---|---|
|
||||
| **Email (SMTP)** | Importants + résumés | P0 | `email` |
|
||||
| **Gotify** | Alertes temps réel | P0 | `gotify` |
|
||||
| **In-app (SignalR)** | Badge UI | P0 | Direct (pas Hangfire) |
|
||||
|
||||
### 8.2 Types d'Événements Notifiables
|
||||
|
||||
| EventType | Email | Gotify | In-App | Cooldown (secondes) |
|
||||
|---|---|---|---|---|
|
||||
| `PersonDetected` | ✅ | ✅ | ✅ | 30 |
|
||||
| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | 300 (5 min) |
|
||||
| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | 30 |
|
||||
| `VehicleDetected` | ✅ | ✅ | ✅ | 60 |
|
||||
| `LicensePlateDetected` | 🟡 | ✅ | ✅ | 60 |
|
||||
| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | 10 |
|
||||
| `CameraOffline` | ✅ | ✅ | ✅ | 600 (10 min) |
|
||||
| `CameraOnline` | 🟡 | 🟡 | ✅ | 600 |
|
||||
| `DailySummary` | ✅ | ❌ | ❌ | N/A |
|
||||
| `WeeklySummary` | ✅ | ❌ | ❌ | N/A |
|
||||
|
||||
### 8.3 Rate Limiting Notifications
|
||||
|
||||
```csharp
|
||||
public class NotificationRateLimiter
|
||||
{
|
||||
private readonly IMemoryCache _cache;
|
||||
|
||||
public bool ShouldSend(Guid cameraId, EventType type, Guid? trackId)
|
||||
{
|
||||
var key = $"notif-rate:{cameraId}:{type}:{trackId ?? Guid.Empty}";
|
||||
var count = _cache.GetOrCreate(key, entry =>
|
||||
{
|
||||
entry.SlidingExpiration = TimeSpan.FromMinutes(1);
|
||||
return 0;
|
||||
});
|
||||
|
||||
if (count >= 20) return false; // Max 20 events/min/camera/type
|
||||
|
||||
_cache.Set(key, count + 1, TimeSpan.FromMinutes(1));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 8.4 Templates
|
||||
|
||||
- Moteur : Scriban (Markdown → HTML pour email)
|
||||
- Stockés en DB (table `NotificationTemplate`)
|
||||
- Éditables depuis l'UI Admin
|
||||
- Fallback : fr → en → template par défaut hardcodé
|
||||
- Signature : `[Heimdall]` dans le sujet
|
||||
Le détail historique de cette partie a été retiré pour éviter de confondre
|
||||
les propositions de 2026-07-16 avec les fonctions livrées.
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 9 : Application web installable (PWA)
|
||||
|
||||
La cible est l’interface web existante, partagée entre ordinateur et mobile : manifeste, icônes, service worker limité aux ressources publiques, page hors connexion, ergonomie tactile, reconnexion et Web Push. Les contrôles d’accès restent côté serveur. Le cache des données privées et le fonctionnement métier hors ligne ne sont pas inclus dans la première étape.
|
||||
La cible est l’interface web existante, partagée entre ordinateur et mobile : manifeste, icônes, service worker limité aux ressources publiques, page hors connexion, ergonomie tactile, reconnexion et Web Push. À ce jour, le manifeste, le worker borné et la page statique hors connexion sont livrés; Web Push et la consultation métier hors ligne restent à implémenter. Les contrôles d’accès restent côté serveur. Le cache des données privées et le fonctionnement métier hors ligne ne sont pas inclus dans le socle actuel.
|
||||
|
||||
Spécification actuelle : [audit et plan PWA](pwa.md).
|
||||
|
||||
@@ -939,8 +934,15 @@ Spécification actuelle : [audit et plan PWA](pwa.md).
|
||||
|
||||
## PARTIE 10 : Plan d'Implémentation Optimisé
|
||||
|
||||
> **Plan historique daté du 2026-07-16, pas un état d'avancement.** Les phases,
|
||||
> livrables et scénarios vidéo ci-dessous décrivent la proposition d'origine;
|
||||
> consulter les guides actuels liés en tête avant d'inférer ce qui est livré.
|
||||
|
||||
### 10.1 7 Étapes Incrémentales
|
||||
|
||||
> Chaque phase et son encadré « Fonctionnel à la fin » ci-dessous décrivent le
|
||||
> plan du 2026-07-16, pas un état vérifié de l'implémentation actuelle.
|
||||
|
||||
Le plan est structuré en **7 étapes**, chacune produisant un logiciel fonctionnel et testable.
|
||||
|
||||
| Étape | Phases | Nom | Livrable |
|
||||
@@ -1011,6 +1013,9 @@ Phase 3 — CI/CD
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Phase 4 — Domain Model (entités multi-site uniquement)
|
||||
> **Inventaire du plan historique.** `NotificationTemplate` existe comme
|
||||
> entité, mais cette entrée ne décrit pas un éditeur livré ni une intégration
|
||||
> Gotify; voir le [guide des notifications actuelles](notifications.md).
|
||||
├── Entités CŒUR : Site, Agent (avec ApiKeyHash, ApiKeyPrefix)
|
||||
├── Entités AUTH : User, Role (Identity), UserSite, ApiKey, AuditLog
|
||||
├── Entités MÉTIER (définies mais migrations seules, pas de logique) :
|
||||
@@ -1390,6 +1395,10 @@ Phase 13 — API Caméras + ONVIF
|
||||
│ • Soft delete : caméra dans la corbeille, pas vraiment supprimée
|
||||
│ • Découverte ONVIF réseau : scan automatique des caméras
|
||||
|
||||
> **Phases 14 et 15 ci-dessous : plan historique, pas état de livraison.**
|
||||
> Le `StreamingHub` et le signaling SDP/ICE décrits ici ne sont pas mappés;
|
||||
> voir les [cinq routes SignalR actuelles](signalr-usage.md).
|
||||
|
||||
Phase 14 — SignalR Hubs (temps réel)
|
||||
├── 5 hubs : Events, Streaming, Monitoring, Notifications, Admin
|
||||
├── EventsHub :
|
||||
@@ -1448,6 +1457,9 @@ Phase 14 — SignalR Hubs (temps réel)
|
||||
│ • User voit UNIQUEMENT ses sites assignés
|
||||
│ • Le signaling WebRTC est prêt pour l'Étape 3
|
||||
|
||||
> **Scénarios de phase historiques, pas des contrats ou preuves d'exécution.**
|
||||
> Les exemples de `StreamingHub`, SDP/ICE, groupes et latence ne décrivent pas
|
||||
> les routes ni le transport vidéo livrés.
|
||||
|
||||
═══════════════════════════════════════════════════════════════════════
|
||||
ÉTAPE 3 — VIDÉO + IA
|
||||
@@ -1455,6 +1467,10 @@ Phase 14 — SignalR Hubs (temps réel)
|
||||
═══════════════════════════════════════════════════════════════════════
|
||||
|
||||
Phase 15 — Agent Vidéo (capture + streaming)
|
||||
> **Scénario vidéo historique, non implémenté tel que décrit.** P2P SIPSorcery,
|
||||
> Coturn obligatoire et objectifs de latence ci-dessous ne sont pas des
|
||||
> comportements ni des mesures livrés. Le chemin actuel est décrit en D6.
|
||||
|
||||
├── FFmpeg capture (passthrough H264, zerolatency)
|
||||
│ ffmpeg -rtsp_transport tcp -buffer_size 0 -max_delay 0 \
|
||||
│ -i rtsp://... -g 1 -tune zerolatency \
|
||||
@@ -1710,68 +1726,14 @@ Phase 17 — API Events + Persons + Vehicles
|
||||
│ • Tout est filtré par site-scope (User voit ses sites)
|
||||
│ • Données accessibles via API pour l'UI (Étape 5)
|
||||
|
||||
Phase 18 — Notifications
|
||||
├── SendNotificationEmailJob (SMTP, queue=email, retry 3x)
|
||||
├── SendNotificationGotifyJob (queue=gotify)
|
||||
├── NotificationRateLimiter (IMemoryCache, max 20 events/min/camera)
|
||||
├── DetectionCooldownService (cooldown par type d'événement)
|
||||
├── Scriban templates (DB + fallback hardcodé fr → en)
|
||||
├── Hiérarchie des notifications :
|
||||
│ ├── "PersonDetected" → Email + Gotify (si configuré)
|
||||
│ ├── "UnknownPerson" → Email + Gotify + In-app (badge rouge)
|
||||
│ ├── "VehicleDetected" → Email (si config) + Gotify
|
||||
│ ├── "CameraOffline" → Email + Gotify (alerte admin)
|
||||
│ └── "MotionDetected" → SILENCIEUX (in-app sans notif)
|
||||
├── Verify: notifications flows green
|
||||
│
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│
|
||||
│ ┌─ SCÉNARIO NOTIFICATION ──────────────────────────────────────┐
|
||||
│ │ │
|
||||
│ │ 1. Personne détectée devant la caméra "Entrée" │
|
||||
│ │ → Événement créé (Phase 16) │
|
||||
│ │ │
|
||||
│ │ 2. Central envoie SendNotificationJob à Hangfire │
|
||||
│ │ → Queue "email" : SendNotificationEmailJob │
|
||||
│ │ → Queue "gotify" : SendNotificationGotifyJob │
|
||||
│ │ │
|
||||
│ │ 3. SendNotificationEmailJob : │
|
||||
│ │ → Render template Scriban : "Personne détectée" │
|
||||
│ │ → Sujet : "[Heimdall] Personne détectée — Entrée" │
|
||||
│ │ → Corps : snapshot incluse (embed) + heure + lieu │
|
||||
│ │ → SMTP : envoi à tous les users configurés │
|
||||
│ │ │
|
||||
│ │ 4. SendNotificationGotifyJob : │
|
||||
│ │ → POST Gotify API : "Personne détectée - Entrée" │
|
||||
│ │ → Priorité : 5 (haute) │
|
||||
│ │ │
|
||||
│ │ 5. SignalR NotificationsHub envoie NewNotification │
|
||||
│ │ → Groupe "notif-{userId}" │
|
||||
│ │ → Badge dans l'UI : "3 notifications non lues" │
|
||||
│ │ │
|
||||
│ │ 6. RateLimiter : max 20 notifs/min/camera │
|
||||
│ │ → Si seuil atteint → pas de nouvelle notification │
|
||||
│ │ → Log "Rate limit atteint pour camera guid-cam-1" │
|
||||
│ │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ ┌─ CONFIGURER SES NOTIFICATIONS ───────────────────────────────┐
|
||||
│ │ PUT /api/auth/profile │
|
||||
│ │ { │
|
||||
│ │ "notificationConfig": { │
|
||||
│ │ "emailEnabled": true, │
|
||||
│ │ "gotifyEnabled": true, │
|
||||
│ │ "subscribedEvents": ["personDetected", "unknownPerson", │
|
||||
│ │ "vehicleDetected", "cameraOffline"],│
|
||||
│ │ "dailyDigest": true │
|
||||
│ │ } │
|
||||
│ │ } │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ • 3 canaux : Email, Gotify, In-app (SignalR)
|
||||
│ • Rate limiting : pas de spam même en rafale
|
||||
│ • Templates personnalisables par l'Admin
|
||||
│ • Chaque user choisit ses types d'événements
|
||||
> **Phase 18 — scénario historique (non état livré).** La conception initiale
|
||||
> Gotify/Scriban ci-dessous a été retirée; voir [l’état courant des
|
||||
> notifications](notifications.md).
|
||||
|
||||
Phase 18 — Notifications (historique)
|
||||
> Détails de cette proposition retirés : ils ne décrivent pas les services,
|
||||
> queues ni contrats actuellement livrés.
|
||||
|
||||
|
||||
Phase 19 — Jobs Métier (retention, cleanup)
|
||||
├── RetentionCheckJob (quotidien 3h, queue=maintenance)
|
||||
@@ -1918,6 +1880,11 @@ Phase 21 — Blazor UI Dashboard + Sites
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
|
||||
Phase 22 — Blazor UI Events + Persons + Live
|
||||
> **Maquette de conception historique, pas le routage ou les mesures actuels.**
|
||||
> La vidéo est intégrée à la page détail caméra; les estimations de latence et
|
||||
> le plafond P2P ci-dessous n'ont pas été validés et ne décrivent pas le relay
|
||||
> MediaMTX livré.
|
||||
|
||||
├── Events list (Route: /events)
|
||||
│ ├── Table paginée (50/page) avec filtres :
|
||||
│ │ Site (MudSelect), Type (MudSelect), Date (MudDateRangePicker)
|
||||
@@ -1942,6 +1909,10 @@ Phase 22 — Blazor UI Events + Persons + Live
|
||||
│ └── Timeline : barre des 30 dernières minutes
|
||||
├── Verify: Playwright events+live green
|
||||
│
|
||||
> **Maquette illustrative historique.** La route, les contrôles qualité,
|
||||
> snapshots/timeline, reconnexion et chiffres de latence ci-dessous ne sont
|
||||
> pas des affirmations sur l'UI ou les performances livrées.
|
||||
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│
|
||||
│ ┌─ LIVE VIDÉO ─────────────────────────────────────────────────┐
|
||||
@@ -1968,6 +1939,11 @@ Phase 22 — Blazor UI Events + Persons + Live
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
|
||||
Phase 23 — Blazor UI Admin
|
||||
> **Maquette historique, pas l’interface livrée.** Le dashboard/configuration
|
||||
> consolidés et le réglage Gotify ci-dessous ne sont pas des routes ou écrans
|
||||
> actuels. Consulter [`ui-pages.md`](ui-pages.md), [`auth-roles.md`](auth-roles.md)
|
||||
> et [les réglages de notification livrés](notifications.md).
|
||||
|
||||
├── Users management (tab Utilisateurs)
|
||||
│ ├── Liste des users avec rôle, email, 2FA status
|
||||
│ ├── [Modifier le rôle], [Reset 2FA], [Supprimer]
|
||||
@@ -2011,6 +1987,11 @@ Phase 23 — Blazor UI Admin
|
||||
═══════════════════════════════════════════════════════════════════════
|
||||
|
||||
Phase 24 — Production Hardening
|
||||
> **Critères et scénarios historiques, pas des résultats d'acceptance.** Les
|
||||
> capacités, objectifs k6, seuils de latence, exemples de backup et assertions
|
||||
> « fonctionnel » ci-dessous ne prouvent pas l'implémentation actuelle, un
|
||||
> déploiement, ni un résultat de test.
|
||||
|
||||
├── Rate limiting (AspNetCoreRateLimit)
|
||||
│ ├── Auth : 5 tentatives/15min par IP
|
||||
│ ├── API : 100 requêtes/min par client
|
||||
@@ -2042,6 +2023,10 @@ Phase 24 — Production Hardening
|
||||
│ └── Pas de perte de snapshots sous charge normale
|
||||
├── Verify: k6 green, backup restore test OK
|
||||
│
|
||||
> **Résultats attendus de conception, jamais preuve de test/déploiement.** Les
|
||||
> valeurs k6 ci-dessus sont des objectifs; le scénario backup ci-dessous
|
||||
> précède le client réellement décrit dans `docker/backup/README.md`.
|
||||
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│
|
||||
│ ┌─ HEALTH CHECKS ──────────────────────────────────────────────┐
|
||||
@@ -2063,6 +2048,9 @@ Phase 24 — Production Hardening
|
||||
│ │ "message": "Analyse IA unavailable"} │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
> **Exemple de backup historique, pas procédure actuelle ni résultat de restore.**
|
||||
> Voir le [guide backup livré](../docker/backup/README.md).
|
||||
|
||||
│ ┌─ BACKUP ─────────────────────────────────────────────────────┐
|
||||
│ │ Quotidien 2h : pg_dump → RustFS backup/heimdall_YYYY-MM-DD.sql.gz │
|
||||
│ │ Hebdomadaire dimanche 3h : mc mirror → backup/ (versionné) │
|
||||
@@ -2075,6 +2063,9 @@ Phase 24 — Production Hardening
|
||||
│ │ 5. Vérifier les sites, agents, events toujours présents │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
> **Objectifs de charge non mesurés et non validés.** Aucun seuil ci-dessous
|
||||
> n'est un SLO ou un résultat de production.
|
||||
|
||||
│ ┌─ LOAD TEST (k6) ─────────────────────────────────────────────┐
|
||||
│ │ objectif : 10 agents, 50 caméras, 20 viewers simultanés │
|
||||
│ │ │
|
||||
@@ -2133,6 +2124,10 @@ CPU; l'inférence GPU nécessite encore une image et un runtime dédiés.
|
||||
|
||||
## PARTIE 12 : Tests
|
||||
|
||||
> **Scénarios de test historiques (2026-07-16), pas résultats ni couverture
|
||||
> actuelle.** La référence `gotify` ci-dessous décrit une ancienne conception
|
||||
> de queue; voir [les canaux livrés](notifications.md) et [les jobs actuels](hangfire-usage.md).
|
||||
|
||||
### 12.1 Stack de Test
|
||||
|
||||
| Niveau | Technologie | Couverture |
|
||||
@@ -2233,10 +2228,13 @@ AnalysisWorker: concurrent requests from multiple cameras
|
||||
|
||||
---
|
||||
|
||||
## PARTIE 14 : Correctifs Applicables aux Documents Sources
|
||||
## PARTIE 14 : Historique de consolidation des documents sources
|
||||
|
||||
Les documents suivants contiennent des informations obsolètes ou erronées.
|
||||
**Ce document (`MASTER_SPECIFICATION.md`) fait foi.**
|
||||
Cette section conserve l'état éditorial de la consolidation du 2026-07-16.
|
||||
Le tableau décrit les observations faites à cette date sur les documents sources;
|
||||
il ne constitue pas un inventaire de leurs défauts actuels ni une liste de
|
||||
travail ouverte. Pour le comportement livré, utiliser les sources courantes
|
||||
liées dans l'en-tête de ce document.
|
||||
|
||||
| Document source | Statut | Corrections nécessaires |
|
||||
|---|---|---|
|
||||
@@ -2253,6 +2251,11 @@ Les documents suivants contiennent des informations obsolètes ou erronées.
|
||||
|
||||
## Annexe A : Résumé des 36 Issues Critiques Résolues
|
||||
|
||||
> **Annexe historique de la baseline 2026-07-16**; ses résolutions et noms de
|
||||
> composants ne constituent pas une validation du runtime actuel. Pour les
|
||||
> notifications et queues livrées, voir le [guide notifications](notifications.md)
|
||||
> et le [guide Hangfire](hangfire-usage.md).
|
||||
|
||||
| # | Issue | Source | Résolution |
|
||||
|---|---|---|---|
|
||||
| C2 | Agent Registration ne retourne pas d'API Key | council-agent | ApiKey ajoutée à la réponse |
|
||||
|
||||
+15
-14
@@ -1,7 +1,8 @@
|
||||
# Heimdall — Documentation
|
||||
|
||||
Bienvenue dans la documentation technique de Heimdall, plateforme de
|
||||
vidéosurveillance IA locale, multi-site, auto-hébergée.
|
||||
vidéosurveillance multi-site auto-hébergée. L'analyse ONNX est locale par
|
||||
défaut sur l'Agent; un mode broker distant est configurable.
|
||||
|
||||
---
|
||||
|
||||
@@ -11,7 +12,7 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
|
||||
|---|---|
|
||||
| **Vue d'ensemble** du projet | `docs/specs.md` (Vision, Architecture, Stack) |
|
||||
| **État réel et travaux restants** | [Issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues) |
|
||||
| **Plan d'implémentation historique** (MVP juillet 2026) | `docs/implementation.md` |
|
||||
| **Archive historique de l'implémentation** (MVP juillet 2026) | `docs/implementation.md` |
|
||||
| **Maquettes UI Blazor** détaillées | `docs/ui-pages.md` |
|
||||
| **Application web installable (PWA)** | [Audit et plan PWA](pwa.md) |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) |
|
||||
@@ -20,25 +21,25 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
|
||||
|
||||
| Domaine | Document | Contenu |
|
||||
|---|---|---|
|
||||
| **Sites & Agents** | `docs/specs.md` (§11-12) | Sites, tokens, registration, heartbeat, bootstrap |
|
||||
| **Caméras & IA** | `docs/specs.md` (§14-19) | ONVIF, Imou, FFmpeg, GPU, AI Pipeline, détection |
|
||||
| **Streaming live** | `docs/specs.md` (§13) + `docs/signalr-usage.md` | Architecture cible; consulter l'audit pour l'état livré |
|
||||
| **Enregistrements** | `docs/specs.md` (§20-21) + `docs/hangfire-usage.md` | Stockage cible; le pipeline d'enregistrement vidéo reste à raccorder |
|
||||
| **Événements** | `docs/specs.md` (§16-19) | Personnes, véhicules, plaques, notifications |
|
||||
| **Notifications** | `docs/notifications.md` | Email SMTP, Gotify, templates Markdown i18n |
|
||||
| **Sites & Agents** | [`docs/specs.md`](specs.md) (§5), [`docs/auth-roles.md`](auth-roles.md) | Création du site, enrôlement et heartbeat Agent |
|
||||
| **Caméras & IA** | [`docs/specs.md`](specs.md) (§5), [`docs/gpu-runtime.md`](gpu-runtime.md) | Découverte, analyse ONNX locale par défaut, CUDA NVIDIA optionnel et état de validation matérielle |
|
||||
| **Streaming live** | [`docs/specs.md`](specs.md) (§5), [`docs/ui-pages.md`](ui-pages.md), [`docs/signalr-usage.md`](signalr-usage.md) | Relay Agent vers MediaMTX en RTSP(S), lecture WHEP/WebRTC; validation caméra/réseau réelle suivie dans #161 et #341 |
|
||||
| **Enregistrements** | [`docs/ui-pages.md`](ui-pages.md), API `RecordingsController` | L’Agent segmente le flux principal, envoie les segments terminés au Central, qui les conserve dans le stockage configuré; lecture protégée dans la fiche caméra. Pas de validation caméra réelle revendiquée |
|
||||
| **Événements** | [`docs/specs.md`](specs.md) (§4), [`docs/ui-pages.md`](ui-pages.md), [`docs/notifications.md`](notifications.md) | Modèle d’événement caméra, pages événements et notifications |
|
||||
| **Notifications** | `docs/notifications.md` | Email SMTP, ntfy, centre in-app et préférences utilisateur |
|
||||
|
||||
## 🔧 Domaines techniques
|
||||
|
||||
| Domaine | Document | Contenu |
|
||||
|---|---|---|
|
||||
| **Auth & Rôles** | `docs/auth-roles.md` | Identity, JWT, permissions, UI par rôle, site-scope |
|
||||
| **IA (ONNX)** | `docs/specs.md` | Architecture cible; consulter l'audit pour distinguer les capacités livrées |
|
||||
| **IA (ONNX)** | [`docs/gpu-runtime.md`](gpu-runtime.md), [`docs/specs.md`](specs.md) (§5) | CPU par défaut, image CUDA NVIDIA optionnelle, limites d’inventaire et validation matérielle |
|
||||
| **Hangfire (jobs)** | `docs/hangfire-usage.md` | Configuration actuelle et jobs présents; vérifier l'état des parcours dans l'audit |
|
||||
| **Métriques et alertes** | [Métriques Prometheus](metrics.md) | Endpoints Web/Agent et signaux de santé exportés |
|
||||
| **SignalR (temps réel)** | `docs/signalr-usage.md` | Hubs et contrats documentés; état du streaming live dans l'audit |
|
||||
| **Déploiement Docker** | `docs/specs.md` (§30) | Containers, GPU passthrough, docker-compose |
|
||||
| **Déploiement Docker** | [`docs/specs.md`](specs.md) (§6), [`docs/docker-compose.md`](docker-compose.md) | Services requis et optionnels; l’inférence GPU NVIDIA est une variante Agent optionnelle |
|
||||
| **Docker Compose** | [Déploiement séparé](docker-compose.md) | Central + PostgreSQL requis; Agent et logiciels optionnels séparés |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Profils facultatifs; l'inférence ONNX publiée reste CPU |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Image CPU par défaut; image NVIDIA/CUDA amd64 optionnelle publiée avec manifeste signé; exécution CUDA physique à valider sur matériel |
|
||||
|
||||
## 📐 Structure du projet
|
||||
|
||||
@@ -65,9 +66,9 @@ Heimdall/
|
||||
| `implementation.md` | Plan historique du MVP (juillet 2026); statuts non représentatifs de l'état actuel |
|
||||
| `docker-compose.md` | Déploiement Central, Agents autonomes et logiciels facultatifs |
|
||||
| `ui-pages.md` | Pages Blazor (MudBlazor) : maquettes ASCII, composants, états |
|
||||
| `pwa.md` | Audit PWA du serveur Blazor, architecture cible et plan de réalisation |
|
||||
| `auth-roles.md` | Auth : 2 user types, permissions, site-scope, UI visibility |
|
||||
| `notifications.md` | Email (SMTP), Gotify, templates Markdown i18n, hangfile queue |
|
||||
| `pwa.md` | État livré de la PWA, limites hors ligne et feuille de route Web Push |
|
||||
| `auth-roles.md` | Auth : rôles Admin/Supervisor/Viewer, permissions et accès par site/caméra |
|
||||
| `notifications.md` | Canaux SMTP/ntfy, centre in-app, préférences et résumés planifiés |
|
||||
| `hangfire-usage.md` | Description des jobs Hangfire présents au Central et à l’Agent |
|
||||
| `metrics.md` | Métriques exportées par Central et les Agents, avec leur portée et limites |
|
||||
| `signalr-usage.md` | Hubs SignalR et contrats documentés; voir l’audit pour les capacités effectivement livrées |
|
||||
|
||||
+120
-211
@@ -8,61 +8,68 @@
|
||||
|
||||
---
|
||||
|
||||
## 1. Types d'utilisateurs
|
||||
## 1. Rôles disponibles
|
||||
|
||||
### Admin
|
||||
Heimdall définit trois rôles (`Admin`, `Supervisor`, `Viewer`), listés dans
|
||||
[`AppRoles.All`](../src/Heimdall.Infrastructure/Security/AppPermissions.cs) et
|
||||
[`UserRole`](../src/Heimdall.Domain/Enums/UserRole.cs). Les permissions par
|
||||
défaut viennent de [`AppPermissions.RolePermissions`](../src/Heimdall.Infrastructure/Security/AppPermissions.cs); les
|
||||
permissions des rôles non-Admin peuvent être ajustées par un administrateur.
|
||||
Le rôle détermine les capacités, tandis que l’accès effectif aux sites et aux
|
||||
caméras est vérifié séparément par les services d’accès aux ressources.
|
||||
|
||||
| Propriété | Valeur |
|
||||
| Rôle | Capacités par défaut |
|
||||
|---|---|
|
||||
| Accès | **Tous les sites** sans restriction |
|
||||
| Configuration | Peut tout configurer (sites, caméras, IA, stockage, notifications) |
|
||||
| Administration | Gère les users, les rôles, les clés API, les jobs Hangfire |
|
||||
| Visibilité UI | **Toutes les pages** (y compris Admin) |
|
||||
| Permissions | Toutes les permissions automatiquement |
|
||||
| Sites | Non restreint — voit tous les sites, toutes les caméras |
|
||||
| **Admin** | Toutes les permissions, y compris l’administration globale. |
|
||||
| **Supervisor** | Lecture des sites, caméras, événements, personnes et véhicules; live, enregistrement et snapshots caméra; écriture caméra/personne/véhicule. Aucun droit `Admin.*` par défaut. |
|
||||
| **Viewer** | Lecture des sites, caméras, live, événements, personnes et véhicules. Aucun droit d’écriture, d’enregistrement, de snapshot ni `Admin.*` par défaut. |
|
||||
|
||||
### User
|
||||
|
||||
| Propriété | Valeur |
|
||||
|---|---|
|
||||
| Accès | **1 ou N sites** assignés par l'Admin |
|
||||
| Configuration | Aucune — lecture seule ou actions limitées |
|
||||
| Administration | Aucun accès |
|
||||
| Visibilité UI | Pages selon ses permissions + uniquement ses sites |
|
||||
| Permissions | Définies par rôle + site |
|
||||
| Scope | Restreint aux sites qui lui sont assignés |
|
||||
Les rôles Supervisor et Viewer n’impliquent pas l’accès à tous les sites : les
|
||||
endpoints et handlers appliquent les affectations et contrôles de ressource via
|
||||
[`ICameraAccessService`](../src/Heimdall.Application/Services/ICameraAccessService.cs).
|
||||
Voir la matrice de permissions et la section sur `ICameraAccessService` ci-dessous.
|
||||
|
||||
---
|
||||
|
||||
## 2. Modèle de données
|
||||
|
||||
```csharp
|
||||
// IdentityUser de base — pas de modification
|
||||
public class User : IdentityUser<Guid>
|
||||
// Infrastructure/Identity/IdentityAppUser.cs
|
||||
// La classe Identity et ses dépendances restent dans Infrastructure.
|
||||
public sealed class IdentityAppUser : IdentityUser<Guid>
|
||||
{
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public ThemeMode Theme { get; set; } = ThemeMode.Auto;
|
||||
public string? Theme { get; set; } = "Auto";
|
||||
public string Language { get; set; } = "fr";
|
||||
public bool TwoFactorEnabled { get; set; } = false; // TOTP
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public bool MustChangePassword { get; set; }
|
||||
}
|
||||
|
||||
// Relation User → Sites (N-N)
|
||||
// Domain/Entities/UserSite.cs — aucune navigation vers le type Identity.
|
||||
public class UserSite
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public User User { get; set; } = null!;
|
||||
public Guid UserId { get; private set; }
|
||||
public Guid SiteId { get; private set; }
|
||||
public Site Site { get; private set; } = null!;
|
||||
|
||||
public Guid SiteId { get; set; }
|
||||
public Site Site { get; set; } = null!;
|
||||
private UserSite() { } // EF Core
|
||||
|
||||
public UserSite(Guid userId, Guid siteId)
|
||||
{
|
||||
UserId = userId;
|
||||
SiteId = siteId;
|
||||
}
|
||||
}
|
||||
|
||||
// Infrastructure/Data/Configurations/UserSiteConfiguration.cs — relation seulement.
|
||||
builder.HasOne<IdentityAppUser>().WithMany().HasForeignKey(us => us.UserId);
|
||||
|
||||
// Rôles prédéfinis
|
||||
public static class AppRoles
|
||||
{
|
||||
public const string Admin = "Admin";
|
||||
public const string Superviseur = "Superviseur"; // peut voir + agir
|
||||
public const string Viewer = "Viewer"; // lecture seule
|
||||
public const string Supervisor = "Supervisor"; // libellé UI français : Superviseur
|
||||
public const string Viewer = "Viewer"; // lecture seule
|
||||
}
|
||||
```
|
||||
|
||||
@@ -91,19 +98,20 @@ public static class AppPermissions
|
||||
public const string EventRead = "Event.Read";
|
||||
public const string PersonRead = "Person.Read";
|
||||
public const string PersonWrite = "Person.Write";
|
||||
public const string VehicleRead = "Vehicle.Read";
|
||||
public const string VehicleWrite = "Vehicle.Write";
|
||||
|
||||
// Administration
|
||||
public const string AdminManage = "Administration.Manage";
|
||||
public const string AdminUsers = "Administration.Users";
|
||||
public const string AdminApiKeys = "Administration.ApiKeys";
|
||||
public const string AdminJobs = "Administration.Jobs"; // Hangfire dashboard
|
||||
public const string AdminNotifications = "Administration.Notifications"; // templates
|
||||
public const string AdminManage = "Admin.Manage";
|
||||
public const string AdminUsers = "Admin.Users";
|
||||
public const string AdminApiKeys = "Admin.ApiKeys";
|
||||
public const string AdminJobs = "Admin.Jobs"; // Hangfire dashboard
|
||||
}
|
||||
```
|
||||
|
||||
### Mapping Rôle → Permissions
|
||||
|
||||
| Permission | Admin | Superviseur | Viewer |
|
||||
| Permission | Admin | Supervisor | Viewer |
|
||||
|---|---|---|---|
|
||||
| Site.Read | ✅ | ✅ | ✅ |
|
||||
| Site.Write | ✅ | ❌ | ❌ |
|
||||
@@ -116,11 +124,12 @@ public static class AppPermissions
|
||||
| Event.Read | ✅ | ✅ | ✅ |
|
||||
| Person.Read | ✅ | ✅ | ✅ |
|
||||
| Person.Write | ✅ | ✅ | ❌ |
|
||||
| Vehicle.Read | ✅ | ✅ | ✅ |
|
||||
| Vehicle.Write | ✅ | ✅ | ❌ |
|
||||
| Admin.Manage | ✅ | ❌ | ❌ |
|
||||
| Admin.Users | ✅ | ❌ | ❌ |
|
||||
| Admin.ApiKeys | ✅ | ❌ | ❌ |
|
||||
| Admin.Jobs | ✅ | ❌ | ❌ |
|
||||
| Admin.Notifications | ✅ | ❌ | ❌ |
|
||||
|
||||
---
|
||||
|
||||
@@ -129,68 +138,30 @@ public static class AppPermissions
|
||||
### Enregistrement
|
||||
|
||||
```csharp
|
||||
// Program.cs
|
||||
builder.Services.AddAuthorization(options =>
|
||||
// Heimdall.Web/Program.cs — ConfigureAuthorizationPolicies
|
||||
builder.Services.AddAuthorizationCore(options =>
|
||||
{
|
||||
// Permission directe
|
||||
foreach (var permission in typeof(AppPermissions).GetFields(
|
||||
BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
|
||||
.Where(f => f.IsLiteral && !f.IsInitOnly)
|
||||
.Select(f => f.GetRawConstantValue() as string)
|
||||
.Where(v => v != null))
|
||||
{
|
||||
options.AddPolicy(permission!, policy =>
|
||||
var allPermissions = AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct();
|
||||
foreach (var permission in allPermissions)
|
||||
options.AddPolicy(permission, policy =>
|
||||
policy.RequireClaim("permission", permission));
|
||||
}
|
||||
|
||||
// Admin a toutes les permissions automatiquement
|
||||
options.AddPolicy("AdminOnly", policy =>
|
||||
// Legacy role-based policy retained for administrative endpoints.
|
||||
options.AddPolicy("AdminUsers", policy =>
|
||||
policy.RequireRole(AppRoles.Admin));
|
||||
});
|
||||
```
|
||||
|
||||
### Vérification site-scope
|
||||
### Vérification site et caméra
|
||||
|
||||
Pour les Users non-Admin, chaque requête sur un site doit vérifier
|
||||
que l'User a accès à ce site :
|
||||
|
||||
```csharp
|
||||
public class SiteAuthorizationHandler : AuthorizationHandler<SiteRequirement, Guid>
|
||||
{
|
||||
private readonly ApplicationDbContext _db;
|
||||
|
||||
protected override async Task HandleRequirementAsync(
|
||||
AuthorizationHandlerContext context,
|
||||
SiteRequirement requirement,
|
||||
Guid siteId)
|
||||
{
|
||||
if (context.User.IsInRole(AppRoles.Admin))
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
return;
|
||||
}
|
||||
|
||||
var userId = context.User.GetUserId();
|
||||
var hasAccess = await _db.UserSites
|
||||
.AnyAsync(us => us.UserId == userId && us.SiteId == siteId);
|
||||
|
||||
if (hasAccess) context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
|
||||
public record SiteRequirement : IAuthorizationRequirement;
|
||||
|
||||
// Usage dans un endpoint :
|
||||
[HttpGet("/api/sites/{siteId}/cameras")]
|
||||
public async Task<IActionResult> GetCameras(
|
||||
Guid siteId,
|
||||
[FromServices] IAuthorizationService auth)
|
||||
{
|
||||
var authResult = await auth.AuthorizeAsync(User, siteId, "SiteAccess");
|
||||
if (!authResult.Succeeded) return Forbid();
|
||||
// ...
|
||||
}
|
||||
```
|
||||
Les endpoints déclarent une policy comme `Camera.Read`, puis transmettent
|
||||
l'identité utilisateur aux queries ou à `ResourceAccess` pour filtrer la
|
||||
ressource demandée. Par exemple, `GET /api/cameras/by-site/{siteId}` est mappé
|
||||
par `CamerasController.ListBySite`; il crée un `GetCamerasBySiteQuery` avec le
|
||||
`userId`. Le handler appelle `ICameraAccessService` et ne retourne que les
|
||||
caméras auxquelles cet utilisateur a accès. Il n'existe pas de route
|
||||
`/api/sites/{siteId}/cameras` dans ce contrôleur ni de handler générique
|
||||
`SiteAuthorizationHandler`.
|
||||
|
||||
---
|
||||
|
||||
@@ -204,147 +175,85 @@ public async Task<IActionResult> GetCameras(
|
||||
| Dashboard | `/` | ✅ Tous sites | ✅ Ses sites | ✅ Ses sites |
|
||||
| Sites liste | `/sites` | ✅ Tous | ✅ Ses sites | ✅ Ses sites |
|
||||
| Site détail | `/sites/{id}` | ✅ | ✅ (si assigné) | ✅ (si assigné) |
|
||||
| Caméra live | `/cameras/{id}/live` | ✅ | ✅ (si site assigné) | ✅ (si site assigné) |
|
||||
| Détail caméra (live-view intégré) | `/cameras/{id}` | ✅ | ✅ (si site assigné) | ✅ (si site assigné) |
|
||||
| Events | `/events` | ✅ Tous | ✅ Ses sites | ✅ Ses sites |
|
||||
| Persons | `/persons` | ✅ | ✅ | ✅ |
|
||||
| Admin | `/admin` | ✅ | ❌ Redirection | ❌ Redirection |
|
||||
| Admin Users | `/admin/users` | ✅ | ❌ | ❌ |
|
||||
| Admin API Keys | `/admin/api-keys` | ✅ | ❌ | ❌ |
|
||||
| Admin Hangfire | `/admin/jobs` | ✅ | ❌ | ❌ |
|
||||
| Admin Notifications | `/admin/notifications` | ✅ | ❌ | ❌ |
|
||||
| Paramètres (dont notifications) | `/settings` | ✅ Admin.Manage | ❌ | ❌ |
|
||||
| Utilisateurs | `/users` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Rôles | `/admin/roles` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Groupes | `/admin/groups` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Agents | `/admin/agents` | ✅ Admin.Users | ❌ | ❌ |
|
||||
| Clés API | `/admin/api-keys` | ✅ Admin.ApiKeys | ❌ | ❌ |
|
||||
| Claims | `/admin/claims` | ✅ Admin.Manage | ❌ | ❌ |
|
||||
| Journaux d'audit | `/audit-logs` | ✅ Admin.Manage | ❌ | ❌ |
|
||||
| Hangfire | `/hangfire` | ✅ Admin.Jobs | ❌ | ❌ |
|
||||
|
||||
La page détail caméra requiert une session authentifiée; les API de données et
|
||||
de live-view appliquent `Camera.Read` et vérifient aussi l'accès effectif à la
|
||||
caméra et à son site. La session live utilise
|
||||
`POST /api/live-media/cameras/{cameraId}/session` et
|
||||
`DELETE /api/live-media/cameras/{cameraId}/session/{sessionId}`. `Camera.Live`
|
||||
reste dans le catalogue des permissions attribuées aux rôles, mais n'est pas la
|
||||
policy appliquée à ces deux endpoints dans le contrôleur actuel.
|
||||
|
||||
### Implementation Blazor
|
||||
|
||||
```csharp
|
||||
// Layout — masquer le menu Admin si pas Admin
|
||||
@if (await AuthorizeService.HasPermissionAsync(AppPermissions.AdminManage))
|
||||
// MainLayout — le groupe Administration apparaît avec l’une de ces permissions.
|
||||
@if (Auth.HasPermission("Admin.Users") || Auth.HasPermission("Admin.Manage"))
|
||||
{
|
||||
<MudNavLink Href="/admin">⚙️ Administration</MudNavLink>
|
||||
}
|
||||
<MudText Typo="Typo.overline">Administration</MudText>
|
||||
|
||||
// Page Events — filtrer par site si User non-Admin
|
||||
@code {
|
||||
protected override async Task OnInitializedAsync()
|
||||
@if (Auth.HasPermission("Admin.Users"))
|
||||
{
|
||||
if (await AuthorizeService.IsAdminAsync())
|
||||
{
|
||||
_sites = await SiteService.GetAllAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_sites = await SiteService.GetMySitesAsync();
|
||||
}
|
||||
<MudNavLink Href="/users">Utilisateurs</MudNavLink>
|
||||
<MudNavLink Href="/admin/groups">Groupes</MudNavLink>
|
||||
<MudNavLink Href="/admin/roles">Rôles</MudNavLink>
|
||||
}
|
||||
|
||||
@if (Auth.HasPermission("Admin.Manage"))
|
||||
{
|
||||
<MudNavLink Href="/admin/claims">Claims</MudNavLink>
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### AuthorizeView
|
||||
|
||||
```razor
|
||||
<AuthorizeView Policy="@AppPermissions.CameraLive">
|
||||
<Authorized>
|
||||
<button @onclick="StartLiveView">📷 Live</button>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
<MudTooltip Text="Accès non autorisé">
|
||||
<button disabled>📷 Live</button>
|
||||
</MudTooltip>
|
||||
</NotAuthorized>
|
||||
</AuthorizeView>
|
||||
```
|
||||
Les pages authentifiées sont enveloppées par `AuthorizeRouteView` dans
|
||||
[`Routes.razor`](../src/Heimdall.Web/Components/Routes.razor); par exemple,
|
||||
[`EventsPage.razor`](../src/Heimdall.Web/Components/Pages/EventsPage.razor)
|
||||
déclare `[Authorize]` et charge les données via `HeimdallApiClient`. Les listes
|
||||
et détails site/caméra ne filtrent pas les ressources selon un `IsAdminAsync`
|
||||
local : les endpoints et queries appliquent les permissions puis
|
||||
[`ResourceAccess`](../src/Heimdall.Web/Security/ResourceAccess.cs) et les
|
||||
services d’accès aux ressources. Les endpoints de session live et la distinction
|
||||
`Camera.Read`/`Camera.Live` sont décrits ci-dessus.
|
||||
|
||||
---
|
||||
|
||||
## 6. API — middleware de scope
|
||||
## 6. API — filtrage des accès caméra
|
||||
|
||||
Un middleware applique le scope site automatiquement sur les requêtes API :
|
||||
|
||||
```csharp
|
||||
public class SiteScopeMiddleware
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
if (context.User.Identity?.IsAuthenticated != true) return;
|
||||
|
||||
// Admin bypass
|
||||
if (context.User.IsInRole(AppRoles.Admin))
|
||||
{
|
||||
context.Items["AllowedSiteIds"] = null; // all
|
||||
return;
|
||||
}
|
||||
|
||||
// User scope
|
||||
var userId = context.User.GetUserId();
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == userId)
|
||||
.Select(us => us.SiteId)
|
||||
.ToListAsync();
|
||||
|
||||
context.Items["AllowedSiteIds"] = siteIds;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Puis dans les repositories/query handlers, filtrer par `AllowedSiteIds` :
|
||||
|
||||
```csharp
|
||||
public class GetEventsQueryHandler : IRequestHandler<GetEventsQuery, PagedResult<EventDto>>
|
||||
{
|
||||
public async Task<PagedResult<EventDto>> Handle(GetEventsQuery request, CancellationToken ct)
|
||||
{
|
||||
var query = _db.Events.AsQueryable();
|
||||
|
||||
// Scope site
|
||||
if (request.AllowedSiteIds != null)
|
||||
query = query.Where(e => request.AllowedSiteIds.Contains(e.SiteId));
|
||||
|
||||
// Si siteId spécifique fourni, vérifier qu'il est dans les allowed
|
||||
if (request.SiteId.HasValue)
|
||||
{
|
||||
if (request.AllowedSiteIds != null &&
|
||||
!request.AllowedSiteIds.Contains(request.SiteId.Value))
|
||||
return new PagedResult<EventDto>(); // vide
|
||||
query = query.Where(e => e.SiteId == request.SiteId.Value);
|
||||
}
|
||||
|
||||
// ... pagination, filtres ...
|
||||
}
|
||||
}
|
||||
```
|
||||
Le runtime n'utilise pas de `SiteScopeMiddleware` global ni de liste
|
||||
`AllowedSiteIds` placée dans `HttpContext`. Les endpoints appliquent leurs
|
||||
policies d'authentification et les queries/services partagés résolvent les
|
||||
droits de ressource à partir des accès courants. Pour les caméras, ce modèle
|
||||
est centralisé dans `ICameraAccessService`/`CameraAccessService`; pour une
|
||||
ressource précise, `ResourceAccess` effectue le contrôle demandé par le
|
||||
contrôleur. Cela inclut les accès directs, les accès de site, les anciennes
|
||||
affectations et les groupes caméra. Voir
|
||||
[`skills/camera-access-groups/SKILL.md`](../skills/camera-access-groups/SKILL.md)
|
||||
pour maintenir cette union sans la réimplémenter dans un contrôleur.
|
||||
|
||||
---
|
||||
|
||||
## 7. JWT Claims
|
||||
|
||||
```csharp
|
||||
// À la génération du token JWT
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new(ClaimTypes.Name, user.DisplayName),
|
||||
new(ClaimTypes.Role, role), // "Admin"
|
||||
};
|
||||
|
||||
// Ajouter toutes les permissions du rôle
|
||||
foreach (var permission in GetPermissionsForRole(role))
|
||||
claims.Add(new Claim("permission", permission));
|
||||
|
||||
// Ajouter les sites accessibles (si non-Admin)
|
||||
if (role != AppRoles.Admin)
|
||||
{
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == user.Id)
|
||||
.Select(us => us.SiteId.ToString())
|
||||
.ToListAsync();
|
||||
foreach (var siteId in siteIds)
|
||||
claims.Add(new Claim("site", siteId));
|
||||
}
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddHours(8),
|
||||
signingCredentials: credentials);
|
||||
```
|
||||
`JwtService.GenerateAccessToken` émet le sujet utilisateur, l'email, le nom,
|
||||
les métadonnées de session, les rôles et les permissions. Il n'embarque pas de
|
||||
liste d'IDs de site ou de caméra. Les droits de ressource restent résolus côté
|
||||
serveur depuis les affectations courantes via `CameraAccessService` et
|
||||
`ResourceAccess`, afin qu'une modification d'accès ne dépende pas d'une liste
|
||||
de sites figée dans un JWT.
|
||||
|
||||
---
|
||||
|
||||
@@ -360,4 +269,4 @@ API respects site scope for non-admin users
|
||||
JWT token contains permissions claims
|
||||
UserSite assignment works correctly
|
||||
Removing user from site revokes access immediately
|
||||
```
|
||||
```
|
||||
+10
-17
@@ -15,7 +15,7 @@
|
||||
│ │
|
||||
│ Hangfire Server │
|
||||
│ ├── Storage: PostgreSQL (Hangfire.PostgreSql) │
|
||||
│ ├── Dashboard: /admin/jobs (authentifié, Admin only) │
|
||||
│ ├── Dashboard: /hangfire (AdminJobs ou rôle Admin) │
|
||||
│ └── Jobs: │
|
||||
│ ├── RetentionCheck (Recurring, daily) │
|
||||
│ ├── S3Cleanup (Recurring, daily) │
|
||||
@@ -467,27 +467,20 @@ public class HangfireInitializer : IHostedService
|
||||
|
||||
Intégré à l'UI Admin, authentifié, pas exposé publiquement :
|
||||
|
||||
La route Central est mappée par `MapHangfireDashboard("/hangfire", ...)` dans
|
||||
`src/Heimdall.Web/Program.cs`. `HangfireAdminAuthorizationFilter` autorise les
|
||||
requêtes authentifiées portant `Admin.Jobs` ou le rôle `Admin`. Le dashboard
|
||||
n'est pas mappé dans l'environnement `Testing`.
|
||||
|
||||
```csharp
|
||||
// Heimdall.Api / Program.cs
|
||||
app.UseHangfireDashboard("/admin/jobs", new DashboardOptions
|
||||
// Heimdall.Web/Program.cs
|
||||
app.MapHangfireDashboard("/hangfire", new DashboardOptions
|
||||
{
|
||||
Authorization =
|
||||
[
|
||||
new HangfireAuthorizationFilter() // vérifie AppPermissions.AdminJobs
|
||||
new HangfireAdminAuthorizationFilter()
|
||||
],
|
||||
StatsPollingInterval = 3000, // 3s
|
||||
DisplayStorageConnectionString = false,
|
||||
DashboardTitle = "Heimdall — Jobs",
|
||||
});
|
||||
|
||||
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
|
||||
{
|
||||
public bool Authorize(DashboardContext context)
|
||||
{
|
||||
var httpContext = context.GetHttpContext();
|
||||
return httpContext.User?.IsInRole(AppRoles.Admin) == true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
@@ -529,4 +522,4 @@ Hangfire dashboard is accessible only to Admin
|
||||
Hangfire dashboard returns 403 for non-Admin
|
||||
Agent jobs are recreated after agent restart
|
||||
Agent InMemory storage does not persist across restarts
|
||||
```
|
||||
```
|
||||
+33
-18
@@ -1,9 +1,24 @@
|
||||
# Heimdall — Plan d'implémentation
|
||||
# Heimdall — Archive historique du plan d'implémentation (MVP, juillet 2026)
|
||||
|
||||
> **Document historique (MVP — juillet 2026).** Les statuts de phases ci-dessous ne reflètent pas l’état courant du dépôt. Pour le suivi à jour, consulter les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
|
||||
> **Archive historique, pas une description de l’état actuel ni un guide à suivre.** Tout le contenu ci-dessous — architecture, chemins, statuts, commandes, endpoints, décomptes de tests et travaux « à faire » — reflète un instantané du MVP rédigé en juillet 2026. Ces informations ne décrivent pas le dépôt courant et ne constituent pas des instructions d’exploitation. Pour l’implémentation actuelle, utiliser les références ci-dessous; pour l’avancement et les travaux ouverts, consulter les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
|
||||
|
||||
**Principe :** On implémente d'abord le **plus simple et le plus important**.
|
||||
La **vidéo live** arrive en dernier dans l'IHM.
|
||||
## Références actuelles
|
||||
|
||||
| Sujet | Source actuelle |
|
||||
|---|---|
|
||||
| Installation Central, Compose et services optionnels | [Guide Docker Compose](docker-compose.md), [skill d’acceptation du déploiement](../skills/deployment-guide-acceptance/SKILL.md) |
|
||||
| CI, builds et publication | [CI Gitea et images](gitea-builds.md), [signatures des mises à jour Agent](agent-release-signing.md) |
|
||||
| Authentification, rôles et permissions | [Guide rôles et permissions](auth-roles.md) |
|
||||
| Pages, routes et navigation UI | [Inventaire des pages UI](ui-pages.md) |
|
||||
| Hubs SignalR et Hangfire | [Guide SignalR](signalr-usage.md), [Guide Hangfire](hangfire-usage.md) |
|
||||
| Vidéo live, caméra et capacités livrées | [État produit courant](specs.md), [guide live view](../skills/webrtc-live/SKILL.md) |
|
||||
| Notifications | [Guide notifications](notifications.md) |
|
||||
| Métriques et alertes | [Guide Prometheus](metrics.md) |
|
||||
| PWA et validation appareils/déploiement | [Audit PWA](pwa.md) |
|
||||
| Backup et restauration | [Guide backup](../docker/backup/README.md) |
|
||||
|
||||
**Principe directeur du plan MVP de juillet 2026 (historique) :** implémenter d'abord le **plus simple et le plus important**.
|
||||
La **vidéo live** était alors prévue en dernier dans l'IHM; cette priorité appartient au plan ancien et ne décrit pas la feuille de route actuelle.
|
||||
|
||||
## Statut d'avancement (MVP — Juillet 2026)
|
||||
|
||||
@@ -157,14 +172,14 @@ Chaque commit build et push les images Docker.
|
||||
push → restore → build → unit tests → integration tests → docker build
|
||||
```
|
||||
|
||||
## Implémentation actuelle
|
||||
## État déclaré dans le plan historique (juillet 2026)
|
||||
|
||||
- **Forgejo Actions** (`./forgejo/workflows/ci.yml`) ✅
|
||||
- Build + Test sur push (branches main, develop) ✅
|
||||
- Docker build (central + agent) sur main ✅
|
||||
- PostgreSQL service pour les tests ✅
|
||||
|
||||
## À faire (v2)
|
||||
## Travaux à faire dans le plan historique (v2, juillet 2026)
|
||||
|
||||
- [ ] multi-arch Docker (linux/amd64 + arm64)
|
||||
- [ ] Push vers registry Docker
|
||||
@@ -231,7 +246,7 @@ UserRole { Admin, Supervisor, Viewer } ✅
|
||||
|
||||
Interfaces, DTOs, validateurs.
|
||||
|
||||
## Implémentation actuelle
|
||||
## État déclaré dans le plan historique (juillet 2026)
|
||||
|
||||
| Composant | Approche | Status |
|
||||
|-----------|----------|--------|
|
||||
@@ -266,7 +281,7 @@ La migration vers CQRS avec MediatR est prévue en v2 si le besoin se fait senti
|
||||
|
||||
Authentification AVANT d'exposer l'API.
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
| Fonctionnalité | Priorité | Status |
|
||||
|---|---|---|
|
||||
@@ -299,7 +314,7 @@ Authentification AVANT d'exposer l'API.
|
||||
|
||||
# Phase 7 — API Sites + Agent Tokens
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
| Méthode | Route | Auth | Status |
|
||||
|---|---|---|---|
|
||||
@@ -319,7 +334,7 @@ Le token d'enregistrement est :
|
||||
|
||||
# Phase 8 — Agent Registration + Heartbeat
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
### Côté Central
|
||||
|
||||
@@ -358,7 +373,7 @@ Reporté après le MVP logiciel.
|
||||
|
||||
# Phase 10 — Camera Management API
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
| Méthode | Route | Auth | Status |
|
||||
|---|---|---|---|
|
||||
@@ -390,7 +405,7 @@ Reportées en v2.
|
||||
|
||||
# Phase 15 — Hangfire Central
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
| Composant | Status |
|
||||
|-----------|--------|
|
||||
@@ -424,7 +439,7 @@ Reportées en v2.
|
||||
|
||||
# Phase 18 — Blazor UI
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
| Page | Route | Auth | Status |
|
||||
|------|-------|------|--------|
|
||||
@@ -479,7 +494,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
|
||||
# Phase 22 — Dashboard KPI
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
| Widget | Source | Status |
|
||||
|--------|--------|--------|
|
||||
@@ -494,7 +509,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
|
||||
# Phase 23 — Production Hardening
|
||||
|
||||
## Implémenté
|
||||
## État déclaré comme implémenté dans le plan historique (juillet 2026)
|
||||
|
||||
- [x] Health checks (/healthz, /readyz)
|
||||
- [x] Rate limiting (Auth: 10/min, API: 200/min)
|
||||
@@ -503,10 +518,10 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
- [x] Documentation API (Scalar UI)
|
||||
- [x] README avec architecture + setup
|
||||
|
||||
## À faire
|
||||
## Travaux ouverts dans le plan historique (juillet 2026)
|
||||
|
||||
- [ ] Serilog + Seq/GlitchTip
|
||||
- [ ] Métriques Prometheus
|
||||
- [x] Export des métriques Prometheus Central/Agent (`/metrics`); le scraping externe et les seuils d'alerte en exploitation restent à configurer et valider par l'opérateur.
|
||||
- [ ] Backup PostgreSQL automatisé
|
||||
- [ ] Backup RustFS (S3 → S3)
|
||||
- [ ] Tests de charge (k6)
|
||||
@@ -514,7 +529,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Git
|
||||
|
||||
---
|
||||
|
||||
## Résumé — Stats MVP
|
||||
## Résumé historique — Stats MVP (juillet 2026)
|
||||
|
||||
| Métrique | Valeur |
|
||||
|----------|--------|
|
||||
|
||||
+34
-464
@@ -1,464 +1,34 @@
|
||||
# Heimdall — Notifications (Email + Gotify + Templates)
|
||||
|
||||
**Stack :** `FluentEmail.Smtp`, `Gotify.NET`, `RazorTemplating` / `Scriban` (Markdown → HTML)
|
||||
|
||||
---
|
||||
|
||||
## 1. Canaux de notification
|
||||
|
||||
| Canal | Usage | Priorité | Bibliothèque |
|
||||
|---|---|---|---|
|
||||
| **Email** (SMTP) | Notifications importantes, résumés | 🔴 Requis | `FluentEmail.Smtp` + `FluentEmail.Razor` |
|
||||
| **Gotify** (push) | Alertes temps réel, notifications rapides | 🟠 Recommandé | `Gotify.NET` |
|
||||
| **In-app** (SignalR) | Notifications silencieuses dans l'UI | 🟢 Requis | SignalR (intégré) |
|
||||
|
||||
---
|
||||
|
||||
## 2. SMTP — Configuration
|
||||
|
||||
Configurable depuis l'UI Admin :
|
||||
|
||||
```csharp
|
||||
public class SmtpConfig
|
||||
{
|
||||
public string Host { get; set; } = "smtp.example.com";
|
||||
public int Port { get; set; } = 587;
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty; // chiffré
|
||||
public bool UseSsl { get; set; } = true;
|
||||
public string FromAddress { get; set; } = "heimdall@example.com";
|
||||
public string FromName { get; set; } = "Heimdall";
|
||||
}
|
||||
```
|
||||
|
||||
Stockée en base (table `AppConfig`), champ `Password` chiffré avec `IDataProtector`.
|
||||
|
||||
Test depuis l'UI : "Envoyer un email de test".
|
||||
|
||||
### Librairies NuGet
|
||||
|
||||
```
|
||||
dotnet add package FluentEmail.Smtp
|
||||
dotnet add package FluentEmail.Razor // templates Razor → HTML
|
||||
// ou
|
||||
dotnet add package Scriban // templates Markdown alternatif
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Gotify — Configuration
|
||||
|
||||
Gotify est un serveur de notification push self-hosted (Docker).
|
||||
|
||||
### Dépendances
|
||||
|
||||
```
|
||||
dotnet add package Gotify.NET
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
```csharp
|
||||
public class GotifyConfig
|
||||
{
|
||||
public string ServerUrl { get; set; } = "http://gotify:8080";
|
||||
public string AppToken { get; set; } = string.Empty; // chiffré
|
||||
public int Priority { get; set; } = 5; // 0-10
|
||||
}
|
||||
```
|
||||
|
||||
### UI Admin
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Notifications │
|
||||
│ │
|
||||
│ ┌──── Email (SMTP) ───────────────────────┐ │
|
||||
│ │ Serveur: [smtp.example.com ] │ │
|
||||
│ │ Port: [587 ] │ │
|
||||
│ │ SSL: [x] │ │
|
||||
│ │ Utilisateur: [notifications@... ] │ │
|
||||
│ │ Mot de passe: [******** ] │ │
|
||||
│ │ De: [heimdall@example.com ] │ │
|
||||
│ │ │ │
|
||||
│ │ [Tester la connexion] │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌──── Gotify ──────────────────────────────┐ │
|
||||
│ │ Serveur: [http://gotify:8080 ] │ │
|
||||
│ │ Token: [******** ] │ │
|
||||
│ │ Priorité: [5 ▼] │ │
|
||||
│ │ │ │
|
||||
│ │ [Tester la connexion] │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌──── Templates ───────────────────────────┐ │
|
||||
│ │ [Modifier les templates ▼] │ │
|
||||
│ └───────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Templates de notification (Markdown)
|
||||
|
||||
### Architecture
|
||||
|
||||
```text
|
||||
Base de données
|
||||
└── NotificationTemplate
|
||||
├── EventType (enum)
|
||||
├── Language ("fr", "en", "de"...)
|
||||
├── Channel ("email", "gotify", "inapp")
|
||||
├── Subject (string, avec variables)
|
||||
└── Body (string, Markdown avec variables)
|
||||
```
|
||||
|
||||
### Template Entity
|
||||
|
||||
```csharp
|
||||
public class NotificationTemplate
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public EventType EventType { get; set; } // PersonDetected, etc.
|
||||
public string Language { get; set; } = "fr"; // "fr", "en", "de"
|
||||
public string Channel { get; set; } = "email"; // "email", "gotify", "inapp"
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
public string BodyMarkdown { get; set; } = string.Empty;
|
||||
public bool IsDefault { get; set; } // template par défaut
|
||||
}
|
||||
```
|
||||
|
||||
### Variables disponibles dans les templates
|
||||
|
||||
| Variable | Description | Exemple |
|
||||
|---|---|---|
|
||||
| `{{SiteName}}` | Nom du site | "Entrepôt A" |
|
||||
| `{{CameraName}}` | Nom de la caméra | "Entrée principale" |
|
||||
| `{{EventType}}` | Type d'événement | "PersonDetected" |
|
||||
| `{{EventTime}}` | Horodatage | "14/07/2026 14:23:05" |
|
||||
| `{{EventTimeAgo}}` | Relatif | "il y a 2 minutes" |
|
||||
| `{{PersonName}}` | Nom de la personne | "Jean Dupont" |
|
||||
| `{{PersonPhotoUrl}}` | Lien photo | `https://heimdall/...` |
|
||||
| `{{VehiclePlate}}` | Plaque | "AA-123-XX" |
|
||||
| `{{VehicleModel}}` | Modèle | "Renault Clio" |
|
||||
| `{{SnapshotUrl}}` | Lien snapshot | `https://heimdall/...` |
|
||||
| `{{EventUrl}}` | Lien vers l'événement | `https://heimdall/events/...` |
|
||||
| `{{SiteUrl}}` | URL du Central | `https://heimdall.example.com` |
|
||||
| `{{AlertCount}}` | Nombre d'alertes (résumé) | "12" |
|
||||
|
||||
### Templates par défaut (fr)
|
||||
|
||||
```markdown
|
||||
=== PersonDetected — email — fr ===
|
||||
Subject: [Heimdall] Personne détectée — {{CameraName}}
|
||||
Body:
|
||||
**🔴 Alerte — Personne détectée**
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Site** | {{SiteName}} |
|
||||
| **Caméra** | {{CameraName}} |
|
||||
| **Date** | {{EventTime}} |
|
||||
| **Personne** | {{PersonName}} |
|
||||
|
||||
Voir l'événement : [{{EventUrl}}]({{EventUrl}})
|
||||
|
||||
---
|
||||
|
||||
=== PersonDetected — email — en ===
|
||||
Subject: [Heimdall] Person detected — {{CameraName}}
|
||||
Body:
|
||||
**🔴 Alert — Person detected**
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Site** | {{SiteName}} |
|
||||
| **Camera** | {{CameraName}} |
|
||||
| **Time** | {{EventTime}} |
|
||||
| **Person** | {{PersonName}} |
|
||||
|
||||
View event: [{{EventUrl}}]({{EventUrl}})
|
||||
|
||||
---
|
||||
|
||||
=== UnknownPerson — gotify — fr ===
|
||||
Subject: Visage inconnu — {{CameraName}}
|
||||
Body:
|
||||
Visage inconnu détecté sur {{CameraName}} ({{SiteName}})
|
||||
à {{EventTime}}.
|
||||
|
||||
---
|
||||
|
||||
=== DailySummary — email — fr ===
|
||||
Subject: [Heimdall] Résumé quotidien — {{SiteName}} — {{EventTime}}
|
||||
Body:
|
||||
**📊 Résumé quotidien — {{SiteName}}**
|
||||
|
||||
Période: {{DateStart}} → {{DateEnd}}
|
||||
|
||||
| Type | Nombre |
|
||||
|---|---|
|
||||
| Personnes détectées | {{PersonCount}} |
|
||||
| Dont connues | {{KnownPersonCount}} |
|
||||
| Dont inconnues | {{UnknownPersonCount}} |
|
||||
| Véhicules détectés | {{VehicleCount}} |
|
||||
| Événements total | {{TotalEventCount}} |
|
||||
|
||||
[Voir le tableau de bord]({{SiteUrl}})
|
||||
```
|
||||
|
||||
### Rendu du template
|
||||
|
||||
```csharp
|
||||
public class NotificationService : INotificationService
|
||||
{
|
||||
private readonly ScribanTemplateEngine _scriban;
|
||||
private readonly IRepository<NotificationTemplate> _templates;
|
||||
|
||||
public async Task<string> RenderAsync(
|
||||
EventType eventType,
|
||||
string language,
|
||||
string channel,
|
||||
Dictionary<string, object> variables)
|
||||
{
|
||||
// 1. Chercher template spécifique (eventType + language + channel)
|
||||
var template = await _templates.FirstOrDefaultAsync(t =>
|
||||
t.EventType == eventType &&
|
||||
t.Language == language &&
|
||||
t.Channel == channel);
|
||||
|
||||
// 2. Fallback : template par défaut de cette langue
|
||||
template ??= await _templates.FirstOrDefaultAsync(t =>
|
||||
t.EventType == eventType &&
|
||||
t.Language == language &&
|
||||
t.IsDefault);
|
||||
|
||||
// 3. Fallback : template anglais
|
||||
template ??= await _templates.FirstOrDefaultAsync(t =>
|
||||
t.EventType == eventType &&
|
||||
t.Language == "en" &&
|
||||
t.IsDefault);
|
||||
|
||||
if (template == null) return string.Empty;
|
||||
|
||||
// 4. Rendre avec Scriban
|
||||
var parsed = Template.Parse(template.BodyMarkdown);
|
||||
var result = await parsed.RenderAsync(variables);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### UI d'édition des templates
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ Templates de notification [Langue: français ▼]
|
||||
│ │
|
||||
│ Événement: [Personne détectée ▼] Canal: [Email ▼] │
|
||||
│ │
|
||||
│ Sujet: │
|
||||
│ ┌──────────────────────────────────────────────────┐ │
|
||||
│ │ [Heimdall] Personne détectée — {{CameraName}} │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Corps (Markdown): │
|
||||
│ ┌──────────────────────────────────────────────────┐ │
|
||||
│ │ **🔴 Alerte — Personne détectée** │ │
|
||||
│ │ │ │
|
||||
│ │ | | | │ │
|
||||
│ │ |---|---| │ │
|
||||
│ │ | **Site** | {{SiteName}} | │ │
|
||||
│ │ | **Caméra** | {{CameraName}} | │ │
|
||||
│ │ │ │
|
||||
│ │ Voir : [{{EventUrl}}]({{EventUrl}}) │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ [Aperçu] [Réinitialiser] [Enregistrer] │
|
||||
│ │
|
||||
│ ── Aperçu ────────────────────────────────────────── │
|
||||
│ De: heimdall@example.com │
|
||||
│ À: test@example.com │
|
||||
│ Sujet: [Heimdall] Personne détectée — Entrée │
|
||||
│ ──────────────────────────────────────────────────── │
|
||||
│ 🔴 Alerte — Personne détectée │
|
||||
│ Site: Entrepôt A | Caméra: Entrée | Date: 14/07... │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Librairies
|
||||
|
||||
```
|
||||
dotnet add package Scriban # Moteur de templates Markdown
|
||||
dotnet add package Scriban.Signed # (si besoin strong name)
|
||||
// ou
|
||||
dotnet add package FluentEmail.Razor # Alternative Razor → HTML
|
||||
dotnet add package FluentEmail.Smtp # Envoi SMTP
|
||||
dotnet add package Gotify.NET # Gotify push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Types d'événements notifiables
|
||||
|
||||
| EventType | Email | Gotify | In-App (SignalR) | Template dispo |
|
||||
|---|---|---|---|---|
|
||||
| `PersonDetected` | ✅ | ✅ | ✅ | Oui |
|
||||
| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | Oui |
|
||||
| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | Oui |
|
||||
| `VehicleDetected` | ✅ | ✅ | ✅ | Oui |
|
||||
| `LicensePlateDetected` | 🟡 | ✅ | ✅ | Oui |
|
||||
| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | Non |
|
||||
| `CameraOffline` | ✅ | ✅ | ✅ | Oui |
|
||||
| `CameraOnline` | 🟡 | 🟡 | ✅ | Oui |
|
||||
| `DailySummary` | ✅ | ❌ | ❌ | Oui |
|
||||
| `WeeklySummary` | ✅ | ❌ | ❌ | Oui |
|
||||
|
||||
---
|
||||
|
||||
## 6. File d'attente des notifications (Hangfire)
|
||||
|
||||
Toutes les notifications passent par Hangfire pour :
|
||||
|
||||
1. Fiabilité (retry si échec SMTP)
|
||||
2. File d'attente (ne pas bloquer le thread de détection)
|
||||
3. Rate limiting (max N emails/min)
|
||||
|
||||
```csharp
|
||||
public class SendNotificationJob
|
||||
{
|
||||
[AutomaticRetry(Attempts = 3, DelaysInSeconds = [60, 300, 900])]
|
||||
public async Task ExecuteAsync(
|
||||
Guid eventId,
|
||||
string channel, // "email", "gotify", "inapp"
|
||||
string language,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var event = await _db.Events.FindAsync(new object[] { eventId }, ct);
|
||||
var variables = await BuildVariablesAsync(event, ct);
|
||||
|
||||
var rendered = await _notificationService.RenderAsync(
|
||||
event.Type, language, channel, variables);
|
||||
|
||||
await channel switch
|
||||
{
|
||||
"email" => await SendEmailAsync(event, rendered, ct),
|
||||
"gotify" => await SendGotifyAsync(event, rendered, ct),
|
||||
"inapp" => await SendInAppAsync(event, rendered, ct),
|
||||
_ => Task.CompletedTask
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Déclenchement depuis le pipeline IA
|
||||
|
||||
```csharp
|
||||
// Dans le handler de détection
|
||||
if (shouldNotify)
|
||||
{
|
||||
BackgroundJob.Enqueue<SendNotificationJob>(j =>
|
||||
j.ExecuteAsync(event.Id, "email", user.Language, CancellationToken.None));
|
||||
BackgroundJob.Enqueue<SendNotificationJob>(j =>
|
||||
j.ExecuteAsync(event.Id, "gotify", user.Language, CancellationToken.None));
|
||||
}
|
||||
|
||||
// Notification in-app = temps réel via SignalR (pas Hangfire)
|
||||
await _signalrHub.SendEventAsync(event);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Configuration par User
|
||||
|
||||
Chaque utilisateur peut configurer ses notifications :
|
||||
|
||||
```csharp
|
||||
public class UserNotificationConfig
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public bool EmailEnabled { get; set; } = true;
|
||||
public bool GotifyEnabled { get; set; } = false;
|
||||
public string EmailAddress { get; set; } = string.Empty;
|
||||
public List<EventType> SubscribedEvents { get; set; } = new();
|
||||
public string Language { get; set; } = "fr";
|
||||
public bool DailyDigest { get; set; } = true;
|
||||
public bool WeeklyDigest { get; set; } = false;
|
||||
}
|
||||
```
|
||||
|
||||
UI User :
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Mes notifications │
|
||||
│ │
|
||||
│ Recevoir les notifications par : │
|
||||
│ [✅] Email : jean@example.com │
|
||||
│ [ ] Gotify │
|
||||
│ │
|
||||
│ M'alerter pour : │
|
||||
│ [✅] Personnes détectées │
|
||||
│ [✅] Visages inconnus │
|
||||
│ [ ] Véhicules │
|
||||
│ [✅] Caméra hors ligne │
|
||||
│ [ ] Mouvement seul │
|
||||
│ │
|
||||
│ Résumés : │
|
||||
│ [✅] Résumé quotidien │
|
||||
│ [ ] Résumé hebdomadaire │
|
||||
│ │
|
||||
│ Langue des notifications : [Français ▼] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Résumés quotidiens/hebdomadaires (Hangfire)
|
||||
|
||||
```csharp
|
||||
// Planifié dans Hangfire
|
||||
RecurringJob.AddOrUpdate<DailyDigestJob>(
|
||||
"daily-digest",
|
||||
j => j.ExecuteAsync(CancellationToken.None),
|
||||
Cron.Daily(8)); // 8h00
|
||||
|
||||
public class DailyDigestJob
|
||||
{
|
||||
public async Task ExecuteAsync(CancellationToken ct)
|
||||
{
|
||||
var users = await _db.Users
|
||||
.Where(u => u.NotificationConfig.DailyDigest)
|
||||
.ToListAsync(ct);
|
||||
|
||||
foreach (var user in users)
|
||||
{
|
||||
var stats = await BuildDailyStatsAsync(user.Id, ct);
|
||||
BackgroundJob.Enqueue<SendNotificationJob>(j =>
|
||||
j.ExecuteAsync(stats, "email", user.NotificationConfig.Language, ct));
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Tests
|
||||
|
||||
```
|
||||
Notification is sent when person detected
|
||||
SMTP failure retries 3 times via Hangfire
|
||||
Gotify notification is sent correctly
|
||||
User can disable email notifications
|
||||
Template rendering replaces all variables
|
||||
Missing variable does not crash (Scriban safe)
|
||||
Template editing in UI saves correctly
|
||||
Template preview shows correct rendering
|
||||
Fallback to default template works
|
||||
Fallback to English template works
|
||||
Daily digest is generated at configured hour
|
||||
User language changes template language
|
||||
Admin can test SMTP connection from UI
|
||||
Admin can test Gotify connection from UI
|
||||
```
|
||||
# Heimdall — Notifications
|
||||
|
||||
## État livré vérifié dans le dépôt
|
||||
|
||||
Les canaux externes déclarés par `NotificationChannel` sont `Email` et `Ntfy`;
|
||||
les notifications in-app sont consultables séparément dans le centre
|
||||
`/notifications`. L’interface utilise les endpoints authentifiés
|
||||
`/api/notifications` et le hub `/hubs/notifications` pour le compteur non lu.
|
||||
Voir [`signalr-usage.md`](signalr-usage.md) pour le contrat du hub.
|
||||
|
||||
Les réglages administrateur se trouvent dans `/settings` (policy
|
||||
`Admin.Manage`) : configuration et test SMTP, configuration et test ntfy. Les
|
||||
préférences de l’utilisateur, dont l’adresse email, l’activation ntfy, le topic,
|
||||
les événements abonnés et les options de résumé, sont éditées dans `/profile`.
|
||||
La livraison email utilise `EmailService`; les notifications push utilisent
|
||||
`NtfyService` et Hangfire. `DailyDigestJob` envoie le résumé quotidien à 8 h;
|
||||
`WeeklyDigestJob` envoie le résumé hebdomadaire le lundi à 8 h, selon les
|
||||
expressions cron enregistrées dans `JobSetup`.
|
||||
|
||||
Ces constats sont une vérification statique des sources, pas une validation de
|
||||
serveur SMTP, de serveur ntfy ni d’un déploiement. La configuration de ces
|
||||
services dépend de l’opérateur.
|
||||
|
||||
Sources principales :
|
||||
|
||||
- [`NotificationChannel`](../src/Heimdall.Domain/Enums/NotificationChannel.cs)
|
||||
- [`NotificationSettingsSection`](../src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor)
|
||||
- [`NotificationsPage`](../src/Heimdall.Web/Components/Pages/NotificationsPage.razor)
|
||||
- [`NotificationsController`](../src/Heimdall.Web/Controllers/NotificationsController.cs)
|
||||
- [`NtfyService`](../src/Heimdall.Infrastructure/Services/NtfyService.cs)
|
||||
- [`EmailService`](../src/Heimdall.Infrastructure/Services/EmailService.cs)
|
||||
- [`DailyDigestJob`](../src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs)
|
||||
- [`WeeklyDigestJob`](../src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs)
|
||||
- [Planifications Hangfire](../src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs)
|
||||
+76
-420
@@ -1,451 +1,107 @@
|
||||
# Heimdall — SignalR : Tous les hubs, events temps réel
|
||||
# SignalR : routes et contrats livrés
|
||||
|
||||
**Stack :** SignalR (intégré à ASP.NET Core) — pas de lib externe supplémentaire
|
||||
Mis à jour le 13 novembre 2026. Ce guide décrit les hubs effectivement mappés par `src/Heimdall.Web/Program.cs`. Un message SignalR est un signal temps réel destiné aux connexions actuellement autorisées; l’API et la base de données restent la source de vérité pour charger l’état et récupérer ce qui a été manqué lors d’une déconnexion.
|
||||
|
||||
---
|
||||
## Routes et authentification
|
||||
|
||||
## 1. Architecture générale
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ SIGNALR CENTRAL │
|
||||
│ │
|
||||
│ /hubs/events → Événements de détection │
|
||||
│ /hubs/streaming → Signaling WebRTC │
|
||||
│ /hubs/monitoring → Status (agents, caméras, alertes) │
|
||||
│ /hubs/notifications→ Notifications in-app │
|
||||
│ /hubs/admin → Changements config (admin broadcast) │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Chaque hub est authentifié : JWT pour les utilisateurs humains, API Key
|
||||
pour les Agents. Les connexions sont groupées par Site et par User pour
|
||||
ne recevoir que les events pertinents.
|
||||
|
||||
---
|
||||
|
||||
## 2. Hub /hubs/events — Événements de détection
|
||||
|
||||
### Connexion
|
||||
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class EventsHub : Hub
|
||||
{
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
// L'User rejoint automatiquement les groupes de ses sites
|
||||
var userId = Context.User.GetUserId();
|
||||
var isAdmin = Context.User.IsInRole(AppRoles.Admin);
|
||||
|
||||
if (isAdmin)
|
||||
{
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, "all-sites");
|
||||
}
|
||||
else
|
||||
{
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == userId)
|
||||
.Select(us => us.SiteId.ToString())
|
||||
.ToListAsync();
|
||||
|
||||
foreach (var siteId in siteIds)
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"site-{siteId}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Événements émis
|
||||
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
| Hub | Route | Authentification | Usage |
|
||||
|---|---|---|---|
|
||||
| `EventCreated` | `EventDto` | Groupe du site | Nouvel événement de détection |
|
||||
| `PersonDetected` | `PersonEventDto` | Groupe du site | Personne reconnue |
|
||||
| `UnknownPerson` | `UnknownPersonDto` | Groupe du site + Admins | Visage inconnu |
|
||||
| `VehicleDetected` | `VehicleEventDto` | Groupe du site | Véhicule détecté |
|
||||
| `LicensePlateRead` | `PlateEventDto` | Groupe du site | Plaque lue |
|
||||
| `MotionDetected` | `MotionDto` | Groupe du site (silencieux) | Mouvement simple |
|
||||
| `ConfigHub` | `/hubs/config` | Clé API associée à un Agent enregistré | Envoyer des changements et commandes de configuration aux Agents |
|
||||
| `EventsHub` | `/hubs/events` | JWT humain | Recevoir les nouveaux événements des caméras auxquelles l’utilisateur a accès |
|
||||
| `MonitoringHub` | `/hubs/monitoring` | JWT humain | Recevoir les changements d’état des sites accessibles ou les signaux réservés aux Admins |
|
||||
| `NotificationsHub` | `/hubs/notifications` | JWT humain | Recevoir les notifications personnelles et le compteur non lu |
|
||||
| `AdminHub` | `/hubs/admin` | JWT humain avec rôle `Admin` | Recevoir les changements administratifs |
|
||||
|
||||
### Exemple d'envoi
|
||||
Il n’existe pas de route `/hubs/streaming` dans le routage actuel. Ce dépôt ne mappe donc pas de `StreamingHub` ni de signaling WebRTC à cette adresse. Les documents de spécification qui décrivent le streaming cible ne constituent pas un contrat d’API livré.
|
||||
|
||||
```csharp
|
||||
// Dans le handler de détection IA
|
||||
public class DetectionResultHandler
|
||||
{
|
||||
private readonly IHubContext<EventsHub> _hub;
|
||||
Les hubs humains exigent le schéma `JwtBearer`; le cookie Web seul n’authentifie pas ces connexions. Pour les transports SignalR qui ne peuvent pas envoyer un en-tête bearer, le gestionnaire JWT accepte `access_token` seulement sur les chemins `/hubs`. Le client Agent passe sa clé API via `AccessTokenProvider`; le gestionnaire `ApiKey` reconnaît ce jeton sur les routes SignalR. Les clients doivent laisser la bibliothèque SignalR gérer le handshake et ne jamais écrire le jeton dans une URL de page, un journal ou un exemple partagé.
|
||||
|
||||
public async Task HandleAsync(DetectionResult result, CancellationToken ct)
|
||||
{
|
||||
var dto = _mapper.Map<EventDto>(result);
|
||||
La validation du JWT vérifie aussi la session de compte. L’authentification seule ne donne pas accès à tous les groupes : chaque méthode de jointure vérifie le type de demandeur et son périmètre. Les broadcasts réévaluent les droits persistés avant d’envoyer le message.
|
||||
|
||||
// Envoyer au groupe du site
|
||||
await _hub.Clients
|
||||
.Group($"site-{result.SiteId}")
|
||||
.SendAsync("EventCreated", dto, ct);
|
||||
## Méthodes invoquées par les clients
|
||||
|
||||
// Si visage inconnu, envoyer aussi aux admins
|
||||
if (result.EventType == EventType.UnknownPerson)
|
||||
{
|
||||
await _hub.Clients
|
||||
.Group("all-sites")
|
||||
.SendAsync("UnknownPerson", dto, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Hub /hubs/streaming — Signaling WebRTC
|
||||
|
||||
**Voir `docs/specs.md` §13 pour le protocole complet.**
|
||||
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class StreamingHub : Hub
|
||||
{
|
||||
/// <summary>
|
||||
/// Agent : s'enregistre comme source de flux pour une caméra
|
||||
/// </summary>
|
||||
public async Task RegisterSource(Guid agentId, Guid cameraId)
|
||||
{
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, $"camera-{cameraId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Browser : demande un flux pour une caméra
|
||||
/// </summary>
|
||||
public async Task RequestStream(Guid cameraId)
|
||||
{
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, $"viewer-{cameraId}");
|
||||
|
||||
// Notifier l'Agent qu'un viewer arrive
|
||||
await Clients.Group($"camera-{cameraId}")
|
||||
.SendAsync("ViewerConnected", Context.ConnectionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Agent → Browser : offre SDP
|
||||
/// </summary>
|
||||
public async Task SendSdp(string sdp, string targetConnectionId)
|
||||
{
|
||||
await Clients.Client(targetConnectionId)
|
||||
.SendAsync("SdpOffer", sdp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Browser → Agent : réponse SDP
|
||||
/// </summary>
|
||||
public async Task SendAnswer(string sdp, string targetConnectionId)
|
||||
{
|
||||
await Clients.Client(targetConnectionId)
|
||||
.SendAsync("SdpAnswer", sdp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Échange ICE candidates (Agent ↔ Browser)
|
||||
/// </summary>
|
||||
public async Task SendIceCandidate(string candidate, string targetConnectionId)
|
||||
{
|
||||
await Clients.Client(targetConnectionId)
|
||||
.SendAsync("IceCandidate", candidate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Browser : arrête de regarder le flux
|
||||
/// </summary>
|
||||
public async Task StopStreaming(Guid cameraId)
|
||||
{
|
||||
await Groups.RemoveFromGroupAsync(
|
||||
Context.ConnectionId, $"viewer-{cameraId}");
|
||||
|
||||
await Clients.Group($"camera-{cameraId}")
|
||||
.SendAsync("ViewerDisconnected", Context.ConnectionId);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Participants
|
||||
|
||||
| Type | Se connecte en tant que | Envoie | Reçoit |
|
||||
| Hub | Méthode | Arguments | Contrôle appliqué |
|
||||
|---|---|---|---|
|
||||
| **Agent** (SIPSorcery) | `RegisterSource` | SendSdp, SendIceCandidate | ViewerConnected, ViewerDisconnected, SdpAnswer, IceCandidate |
|
||||
| **Browser** (Blazor) | `RequestStream` | SendAnswer, SendIceCandidate, StopStreaming | SdpOffer, IceCandidate |
|
||||
| Config | `JoinAgentGroup` | `agentId` (GUID sous forme de chaîne) | La clé API doit correspondre à l’Agent demandé |
|
||||
| Events | `JoinSiteEvents` | `siteId` (GUID sous forme de chaîne) | Demandeur humain; abonnement limité aux caméras accessibles du site; refus si aucune caméra accessible |
|
||||
| Events | `LeaveSiteEvents` | `siteId` (GUID sous forme de chaîne) | Retire les abonnements caméra de cette connexion |
|
||||
| Monitoring | `JoinSiteMonitoring` | `siteId` (GUID sous forme de chaîne) | Demandeur humain ayant accès au site |
|
||||
| Monitoring | `LeaveSiteMonitoring` | `siteId` (GUID sous forme de chaîne) | Retire l’abonnement de cette connexion |
|
||||
| Monitoring | `JoinAdminBroadcast` | Aucun | Administrateur vérifié depuis l’état courant du compte |
|
||||
| Monitoring | `LeaveAdminBroadcast` | Aucun | Retire l’abonnement administratif de cette connexion |
|
||||
| Notifications | `JoinPersonalNotifications` | Aucun | Identité humaine résolue depuis l’état persistant du compte |
|
||||
| Notifications | `LeavePersonalNotifications` | Aucun | Retire l’abonnement personnel de la connexion |
|
||||
| Admin | `JoinAdminBroadcast` | Aucun | JWT de rôle `Admin`, puis vérification du rôle courant |
|
||||
| Admin | `LeaveAdminBroadcast` | Aucun | Retire l’abonnement de cette connexion |
|
||||
|
||||
---
|
||||
Ces méthodes de jointure sont les appels Hub destinés aux clients. Les méthodes `Notify...` visibles sur les classes de service de broadcast sont des méthodes internes utilisées par l’application; elles ne sont pas des méthodes RPC du Hub.
|
||||
|
||||
## 4. Hub /hubs/monitoring — Status temps réel
|
||||
## Messages envoyés par Central aux clients
|
||||
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class MonitoringHub : Hub
|
||||
{
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
var userId = Context.User.GetUserId();
|
||||
var isAdmin = Context.User.IsInRole(AppRoles.Admin);
|
||||
### Configuration des Agents — `/hubs/config`
|
||||
|
||||
if (isAdmin)
|
||||
{
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, "admin-monitoring");
|
||||
}
|
||||
else
|
||||
{
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == userId)
|
||||
.Select(us => us.SiteId.ToString())
|
||||
.ToListAsync();
|
||||
| Message | Arguments | Destinataire |
|
||||
|---|---|---|
|
||||
| `SettingChanged` | `key`, `value` | Agent concerné ou Agents autorisés selon la portée du réglage |
|
||||
| `ConfigReload` | Aucun | Agents autorisés; leur client récupère la configuration complète par l’API |
|
||||
| `DiscoveryScanRequested` | Aucun | Agent concerné |
|
||||
| `AgentUpdateRequested` | Aucun | Agent concerné |
|
||||
| `ManualSnapshotRequested` | `cameraId`, `requestId` | Agent concerné |
|
||||
|
||||
foreach (var siteId in siteIds)
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, $"monitoring-site-{siteId}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
L’Agent attend son enregistrement, ouvre `/hubs/config`, rejoint son groupe, puis charge la configuration par HTTP. Il écoute les changements, retente une connexion initiale en cas d’échec, utilise une reconnexion automatique et relit périodiquement la configuration. Après une reconnexion, le client Agent rejoint de nouveau son groupe.
|
||||
|
||||
### Événements émis
|
||||
### Événements caméra — `/hubs/events`
|
||||
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
|---|---|---|---|
|
||||
| `AgentStatusChanged` | `AgentStatusDto` | Groupe monitoring du site | Agent online/offline |
|
||||
| `CameraStatusChanged` | `CameraStatusDto` | Groupe monitoring du site | Caméra online/offline |
|
||||
| `StorageUsageUpdated` | `StorageDto` | Admin | Espace RustFS mis à jour |
|
||||
| `GpuUsageUpdated` | `GpuDto` | Admin | Utilisation GPU agent (ONNX Runtime) |
|
||||
| `JobStatusChanged` | `JobDto` | Admin | Un job Hangfire échoue |
|
||||
| `SystemHealthChanged` | `HealthDto` | Admin | Health check global |
|
||||
| Message | Payload | Destinataire |
|
||||
|---|---|---|
|
||||
| `EventCreated` | `CameraEventResponse` | Connexions humaines autorisées à lire la caméra de l’événement |
|
||||
|
||||
### Exemple — Agent offline détecté
|
||||
Le client choisit un site avec `JoinSiteEvents`; Central calcule les caméras accessibles et s’abonne aux groupes caméra correspondants. Central revérifie l’accès au moment de chaque diffusion. Le Hub n’envoie pas de replay historique et ne diffuse pas de messages `PersonDetected`, `VehicleDetected`, `MotionDetected` ou `LicensePlateRead` distincts dans son code actuel; ces informations, lorsqu’elles existent, font partie du DTO d’événement chargé par l’API.
|
||||
|
||||
```csharp
|
||||
// Déclenché par le heartbeat timeout
|
||||
BackgroundJob.Schedule<AgentTimeoutJob>(
|
||||
j => j.ExecuteAsync(agentId, CancellationToken.None),
|
||||
TimeSpan.FromSeconds(90));
|
||||
### Monitoring — `/hubs/monitoring`
|
||||
|
||||
public class AgentTimeoutJob
|
||||
{
|
||||
public async Task ExecuteAsync(Guid agentId, CancellationToken ct)
|
||||
{
|
||||
var agent = await _db.Agents.FindAsync(new object[] { agentId }, ct);
|
||||
if (agent == null) return;
|
||||
| Message | Payload | Destinataire |
|
||||
|---|---|---|
|
||||
| `AgentStatusChanged` | `{ agentId, status }` pour un site; `{ siteId, agentId, status }` pour le broadcast Admin | Utilisateurs autorisés du site et Administrateurs |
|
||||
| `CameraStatusChanged` | `{ cameraId, status }` pour un site; `{ siteId, cameraId, status }` pour le broadcast Admin | Utilisateurs autorisés du site et Administrateurs |
|
||||
| `StorageUsageUpdated` | `{ usedPercent, availableBytes }` | Administrateurs abonnés |
|
||||
| `GpuUsageUpdated` | `{ usedPercent, temperature }` | Administrateurs abonnés |
|
||||
| `JobStatusChanged` | `{ jobName, status, duration }` | Administrateurs abonnés |
|
||||
|
||||
if (agent.LastHeartbeat < DateTime.UtcNow.AddSeconds(-90))
|
||||
{
|
||||
agent.Status = AgentStatus.Offline;
|
||||
await _db.SaveChangesAsync(ct);
|
||||
Une connexion doit appeler `JoinSiteMonitoring(siteId)` pour un site ou `JoinAdminBroadcast()` pour les signaux d’administration. Central vérifie le droit d’accès avant inscription et réévalue les destinataires lors de chaque diffusion.
|
||||
|
||||
// Broadcast en temps réel
|
||||
await _hub.Clients
|
||||
.Group($"monitoring-site-{agent.SiteId}")
|
||||
.SendAsync("AgentStatusChanged", new AgentStatusDto
|
||||
{
|
||||
AgentId = agent.Id,
|
||||
Status = "Offline",
|
||||
LastHeartbeat = agent.LastHeartbeat
|
||||
}, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
### Notifications personnelles — `/hubs/notifications`
|
||||
|
||||
---
|
||||
| Message | Payload | Quand |
|
||||
|---|---|---|
|
||||
| `UnreadCount` | `{ count }` | À la jointure personnelle et après un changement du compteur |
|
||||
| `NewNotification` | `NotificationDto` | Nouvelle notification de l’utilisateur |
|
||||
|
||||
## 5. Hub /hubs/notifications — Notifications in-app
|
||||
Le client Web (`NotificationsHubClient`) écoute ces messages et tente une reconnexion automatique. Si aucun JWT n’est disponible (par exemple une session cookie seule) ou si la connexion temps réel échoue, le badge et la page notifications peuvent recharger le compteur via HTTP lors de leur initialisation ou après une action; aucun timer de polling périodique n’est configuré. Rechargez l’état courant par l’API plutôt que de traiter le compteur local comme un historique durable.
|
||||
|
||||
```csharp
|
||||
[Authorize]
|
||||
public class NotificationsHub : Hub
|
||||
{
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
// L'User rejoint son groupe de notifications personnel
|
||||
var userId = Context.User.GetUserId().ToString();
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"notif-{userId}");
|
||||
}
|
||||
### Administration — `/hubs/admin`
|
||||
|
||||
/// <summary>
|
||||
/// L'User marque une notification comme lue
|
||||
/// </summary>
|
||||
public async Task MarkAsRead(Guid notificationId)
|
||||
{
|
||||
await _db.Notifications
|
||||
.Where(n => n.Id == notificationId)
|
||||
.ExecuteUpdateAsync(setters =>
|
||||
setters.SetProperty(n => n.ReadAt, DateTime.UtcNow));
|
||||
}
|
||||
| Message | Payload | Quand |
|
||||
|---|---|---|
|
||||
| `ConfigChanged` | `{ key, oldValue, newValue }` | Réglage administratif modifié |
|
||||
| `CameraAdded` | `{ siteId, cameraId, cameraName }` | Caméra ajoutée |
|
||||
| `CameraRemoved` | `{ siteId, cameraId }` | Caméra supprimée |
|
||||
| `UserRoleChanged` | `{ userId, newRole }` | Rôle d’un utilisateur modifié |
|
||||
|
||||
/// <summary>
|
||||
/// L'User marque toutes ses notifications comme lues
|
||||
/// </summary>
|
||||
public async Task MarkAllAsRead()
|
||||
{
|
||||
var userId = Context.User.GetUserId();
|
||||
await _db.Notifications
|
||||
.Where(n => n.UserId == userId && n.ReadAt == null)
|
||||
.ExecuteUpdateAsync(setters =>
|
||||
setters.SetProperty(n => n.ReadAt, DateTime.UtcNow));
|
||||
Seuls les Administrateurs peuvent établir une connexion Admin et joindre le broadcast. Les destinataires sont revérifiés avant chaque message.
|
||||
|
||||
// Mettre à jour le badge
|
||||
await Clients.Caller.SendAsync("UnreadCount", 0);
|
||||
}
|
||||
}
|
||||
```
|
||||
## Limites et maintenance
|
||||
|
||||
### Événements émis
|
||||
- Les messages sont des signaux, pas une file durable : un client déconnecté doit relire l’état via l’API.
|
||||
- Les abonnements sont suivis par connexion et leur accès est réévalué à l’envoi; ne pas remplacer ce contrôle par un groupe global accessible à tout utilisateur.
|
||||
- Les hôtes et méthodes listés ici sont extraits de `Program.cs`, des classes `*Hub` et des services de broadcast. Les tests unitaires d’isolation ne valident ni un proxy WebSocket, ni une installation réelle.
|
||||
- Avant d’ajouter un hub ou un événement, mettre à jour les tests d’autorisation et ce guide dans le même changement; suivre `skills/signalr-documentation/SKILL.md`.
|
||||
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
|---|---|---|---|
|
||||
| `NewNotification` | `NotificationDto` | Groupe notif-{userId} | Alerte pour cet user |
|
||||
| `UnreadCount` | `int` | Groupe notif-{userId} | Mise à jour badge |
|
||||
| `NotificationRead` | `Guid` | Groupe notif-{userId} | Confirmé par l'user |
|
||||
## Sources locales
|
||||
|
||||
---
|
||||
|
||||
## 6. Hub /hubs/admin — Changements configuration
|
||||
|
||||
```csharp
|
||||
[Authorize(Policy = "AdminOnly")]
|
||||
public class AdminHub : Hub
|
||||
{
|
||||
/// <summary>
|
||||
/// L'Admin rejoint le groupe admin-broadcast
|
||||
/// </summary>
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
await Groups.AddToGroupAsync(
|
||||
Context.ConnectionId, "admin-broadcast");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Événements émis
|
||||
|
||||
| Nom | Payload | Destinataires | Quand |
|
||||
|---|---|---|---|
|
||||
| `ConfigChanged` | `ConfigChangeDto` | Admin broadcast | Modification config globale |
|
||||
| `TemplateUpdated` | `TemplateDto` | Admin broadcast | Template notification modifié |
|
||||
| `UserRoleChanged` | `UserRoleDto` | Admin broadcast | Permission utilisateur modifiée |
|
||||
| `SiteUpdated` | `SiteDto` | Tous les users du site | Site modifié |
|
||||
| `CameraAdded` | `CameraDto` | Tous les users du site | Nouvelle caméra |
|
||||
| `CameraRemoved` | `Guid` | Tous les users du site | Caméra supprimée |
|
||||
|
||||
### Usage côté Blazor
|
||||
|
||||
```csharp
|
||||
// Dans le Layout ou un service injecté
|
||||
public class ConfigChangeListener : IDisposable
|
||||
{
|
||||
private HubConnection? _hub;
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl("/hubs/admin", options =>
|
||||
{
|
||||
options.AccessTokenProvider = () =>
|
||||
_tokenProvider.GetTokenAsync();
|
||||
})
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
_hub.On<ConfigChangeDto>("ConfigChanged", change =>
|
||||
{
|
||||
// Recharger la config concernée
|
||||
_invokeRequired(() =>
|
||||
{
|
||||
switch (change.Type)
|
||||
{
|
||||
case "site": _navigation.Refresh(); break;
|
||||
case "template": _notifService.ReloadTemplates(); break;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await _hub.StartAsync();
|
||||
}
|
||||
|
||||
public void Dispose() => _hub?.DisposeAsync();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Hub Agent — Communication Agent → Central
|
||||
|
||||
Les Agents se connectent aussi via SignalR (pas seulement HTTP REST) :
|
||||
|
||||
```csharp
|
||||
// Côté Agent
|
||||
public class AgentSignalRService : BackgroundService
|
||||
{
|
||||
private HubConnection? _hub;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken ct)
|
||||
{
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl($"{_centralUrl}/hubs/events", options =>
|
||||
{
|
||||
options.AccessTokenProvider = () =>
|
||||
Task.FromResult(_apiKey);
|
||||
})
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
_hub.On<CameraStatusDto>("CameraStatusRequest", async request =>
|
||||
{
|
||||
// Le Central demande le statut d'une caméra
|
||||
var status = await _cameraService.CheckStatusAsync(request.CameraId, ct);
|
||||
await _hub.InvokeAsync("CameraStatusResponse", status, ct);
|
||||
});
|
||||
|
||||
_hub.On<SnapshotRequest>("SnapshotRequest", async request =>
|
||||
{
|
||||
var snapshot = await _cameraService.CaptureSnapshotAsync(
|
||||
request.CameraId, ct);
|
||||
await _hub.InvokeAsync("SnapshotResponse", snapshot, ct);
|
||||
});
|
||||
|
||||
await _hub.StartAsync(ct);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Résumé — Tous les hubs
|
||||
|
||||
| Hub | Route | Auth | Clients | Usage |
|
||||
|---|---|---|---|---|
|
||||
| **EventsHub** | `/hubs/events` | JWT + API Key | Browser + Agent | Événements détection temps réel |
|
||||
| **StreamingHub** | `/hubs/streaming` | JWT + API Key | Browser + Agent | Signaling WebRTC |
|
||||
| **MonitoringHub** | `/hubs/monitoring` | JWT | Browser + Admin | Status agents, caméras, stockage |
|
||||
| **NotificationsHub** | `/hubs/notifications` | JWT | Browser | Notifications in-app |
|
||||
| **AdminHub** | `/hubs/admin` | JWT (Admin only) | Browser (Admin) | Broadcast changements config |
|
||||
|
||||
---
|
||||
|
||||
## 9. Tests
|
||||
|
||||
```
|
||||
EventsHub emits EventCreated to correct site group
|
||||
EventsHub sends UnknownPerson to admin group too
|
||||
StreamingHub relays SDP offer from Agent to Browser
|
||||
StreamingHub relays ICE candidates bidirectionally
|
||||
MonitoringHub sends AgentStatusChanged on timeout
|
||||
MonitoringHub sends CameraStatusChanged on status change
|
||||
NotificationsHub sends NewNotification to correct user
|
||||
NotificationsHub MarkAsRead updates database
|
||||
NotificationsHub MarkAllAsRead resets badge to 0
|
||||
AdminHub ConfigChanged reaches all connected admins
|
||||
AdminHub CameraAdded reaches all users of the site
|
||||
Agent can connect to EventsHub with API key
|
||||
Agent receives SnapshotRequest and responds
|
||||
Hub groups are correctly created per site
|
||||
User without permission receives 403 on connect
|
||||
Disconnected users are removed from groups
|
||||
```
|
||||
- Routes : [`Program.cs`](../src/Heimdall.Web/Program.cs)
|
||||
- Hubs et diffusion : [`src/Heimdall.Web/Hubs`](../src/Heimdall.Web/Hubs)
|
||||
- Client Web notifications : [`NotificationsHubClient.cs`](../src/Heimdall.Web/Services/NotificationsHubClient.cs)
|
||||
- Client Agent configuration : [`ConfigReceiverService.cs`](../src/Heimdall.Agent/Services/ConfigReceiverService.cs)
|
||||
- Authentification API key : [`ApiKeyAuthenticationHandler.cs`](../src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs)
|
||||
- Tests d’accès et d’isolation : [`tests/Heimdall.Web.Tests/Hubs`](../tests/Heimdall.Web.Tests/Hubs)
|
||||
+86
-84
@@ -1,17 +1,18 @@
|
||||
# Heimdall — Spécification technique
|
||||
|
||||
> **Version :** 1.0 | **Target :** .NET 10+ | **Architecture :** Clean Architecture / CQRS / Multi-site / Local AI
|
||||
> **Version :** 1.0 | **Target :** .NET 10+ | **Architecture :** Clean Architecture / CQRS / Multi-site / Agent-local AI par défaut
|
||||
|
||||
---
|
||||
|
||||
# 1. Vision
|
||||
|
||||
Heimdall is a modern self-hosted intelligent video surveillance platform.
|
||||
100% local AI, no cloud dependency, multi-site distributed architecture.
|
||||
Agent inference runs locally by default; a remote analysis broker is configurable.
|
||||
The default deployment does not require a managed cloud service.
|
||||
|
||||
## Pourquoi Heimdall ?
|
||||
|
||||
- **Privacy first** — tout l'IA tourne en local (ONNX Runtime sur agents + Ollama)
|
||||
- **Privacy first** — l'analyse ONNX est locale par défaut sur l'Agent; le mode broker distant est une option de déploiement distincte
|
||||
- **Multi-site** — un Central + N Agents distants
|
||||
- **Économique** — pas d'abonnement cloud, hardware standard
|
||||
- **Pérenne** — .NET 10, Clean Architecture, open source
|
||||
@@ -22,14 +23,14 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
|
||||
|
||||
- Clean Architecture / CQRS / MédiatR
|
||||
- Multi-site : 1 serveur Central + N Agents Docker distants
|
||||
- Live vidéo : WebRTC P2P (SIPSorcery), latence < 500 ms
|
||||
- IA locale : ONNX Runtime (GPU sur agents équipés, mutualisable inter-sites) + Ollama (LLM résumés)
|
||||
- Espace utilisateur : Admin (global) + User (site-scope)
|
||||
- Live vidéo : relais RTSP de l’Agent vers MediaMTX, lecture navigateur WHEP/WebRTC; mesurer la latence avant d’annoncer une cible
|
||||
- Analyse ONNX sur l'Agent : CPU par défaut, CUDA NVIDIA optionnel; AMD/Intel détectés pour l'inventaire ne signifient pas une inférence accélérée. Le mode broker distant est configurable, sans validation inter-sites revendiquée.
|
||||
- Rôles humains : Admin, Supervisor et Viewer; permissions par rôle, avec contrôle distinct du périmètre site/caméra sur chaque ressource
|
||||
- Stockage : RustFS/S3 centralisé
|
||||
- Temps réel : SignalR (5 hubs)
|
||||
- Jobs planifiés : Hangfire (Central PGSQL + Agent InMemory)
|
||||
- Stack : .NET 10, Blazor MudBlazor, PostgreSQL
|
||||
- Pas de cloud, pas de dépendance externe
|
||||
- Déploiement auto-hébergé; aucun service cloud géré n'est requis par défaut
|
||||
|
||||
---
|
||||
|
||||
@@ -40,16 +41,16 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
|
||||
│ HEIMDALL CENTRAL │
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
|
||||
│ │ API │ │ Web │ │ Workers │ │ Broker IA │ │
|
||||
│ │ REST + │ │ Blazor │ │ Hangfire │ │ Ollama │ │
|
||||
│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ RustFS │ │
|
||||
│ │ API │ │ Web │ │ Workers │ │ MediaMTX │ │
|
||||
│ │ REST + │ │ Blazor │ │ Hangfire │ │ RustFS │ │
|
||||
│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ Live media │ │
|
||||
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ └──────────────┴─────────────┘ │
|
||||
│ │ PostgreSQL / RustFS │
|
||||
└─────────────────────────┼────────────────────────────────────────┘
|
||||
│
|
||||
HTTPS REST + SignalR (signaling)
|
||||
HTTPS REST + SignalR (configuration/événements; pas le média vidéo)
|
||||
│
|
||||
┌───────────┴───────────┐
|
||||
│ │
|
||||
@@ -57,47 +58,37 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
|
||||
│ Agent A │ │ Agent B │
|
||||
│ (site distant) │ │ (site distant) │
|
||||
│ │ │ │
|
||||
│ SIPSorcery │ │ SIPSorcery │
|
||||
│ WebRTC Peer │ │ WebRTC Peer │
|
||||
│ FFmpeg capture │ │ FFmpeg capture │
|
||||
│ RTSP publish │ │ RTSP publish │
|
||||
│ Hangfire memory │ │ Hangfire memory │
|
||||
└────────┬────────┘ └────────┬────────┘
|
||||
│ │
|
||||
P2P WebRTC (SRTP/H264) │
|
||||
◄══════════════════════════════►│
|
||||
Navigateur
|
||||
└─────────────┬────────┘
|
||||
│ RTSP(S) publication
|
||||
▼
|
||||
MediaMTX
|
||||
▲
|
||||
│ WHEP / WebRTC (lecture)
|
||||
Navigateur
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 4. Domain Model — Entités principales
|
||||
|
||||
```
|
||||
Site Agent Camera
|
||||
├── Id (Guid) ├── Id (Guid) ├── Id (Guid)
|
||||
├── Name ├── SiteId (FK) ├── SiteId (FK)
|
||||
├── Address ├── Name ├── Name
|
||||
├── Timezone ├── Hostname ├── Manufacturer
|
||||
├── Enabled ├── Version ├── Model
|
||||
└── Registration ├── Status ├── RtspUrl
|
||||
Token (hash) │ (Online/Offline/Err) ├── Status
|
||||
TokenPlain ├── LastHeartbeat ├── Capabilities
|
||||
TokenExpiresAt ├── PublicIp │ (Ptz, Audio, Motion)
|
||||
└── Capabilities ├── Credentials (encrypted)
|
||||
HasGpu, CpuCores └── StoragePolicyId
|
||||
Résumé des principaux types et propriétés représentatives; les noms suivent
|
||||
les entités actuelles dans `Heimdall.Domain` et ne remplacent pas leur modèle
|
||||
complet.
|
||||
|
||||
Person Vehicle Event
|
||||
├── Id ├── Id ├── Id
|
||||
├── Name ├── LicensePlate ├── SiteId
|
||||
├── Photo ├── PersonId (FK) ├── CameraId
|
||||
├── IsUnknown ├── Make ├── Type (enum)
|
||||
├── FaceSamples ├── Model ├── Timestamp
|
||||
└── Notes └── Color ├── SnapshotPath
|
||||
└── Metadata (jsonb)
|
||||
| Type | Propriétés et relations principales |
|
||||
|---|---|
|
||||
| `Site` | `Name`, `Address`, `Timezone`, `Enabled`, `RegistrationTokenHash`, `TokenExpiresAt`. Seul le hash du jeton d’enrôlement est persisté; la valeur brute est renvoyée lors de la création ou régénération. |
|
||||
| `Agent` | `SiteId`, `Name`, `Hostname`, `Version`, `Status`, `LastHeartbeat`, `ApiKeyHash`, `ApiKeyPrefix`; inclut aussi les relevés d’inventaire matériel et système. |
|
||||
| `Camera` | `SiteId`, `AgentId`, `Name`, `RtspUrl`, `SubRtspUrl`, `Status`, `Capabilities`, `StoragePolicyId`; les credentials résident dans l’entité liée `CameraCredentials`. |
|
||||
| `Person` / `KnownFace` | `Person.DisplayName`, `PhotoUrl`, `Category`, `IsWatchlisted`; les embeddings appartiennent aux entités liées `KnownFace`. |
|
||||
| `Vehicle` | `LicensePlate`, `PersonId`, `Make`, `Model`, `Color`. |
|
||||
| `CameraEvent` | `CameraId`, `AgentId`, `Type`, `Confidence`, `OccurredAt`, références de snapshot/stockage, `MetadataJson`; peut référencer une personne, un véhicule et un enregistrement. |
|
||||
|
||||
Enum: CameraStatus, AgentStatus, EventType, StorageProvider
|
||||
Enum: GpuAcceleration, ThemeMode
|
||||
```
|
||||
Sources : [`Site`](../src/Heimdall.Domain/Entities/Site.cs), [`Agent`](../src/Heimdall.Domain/Entities/Agent.cs), [`Camera`](../src/Heimdall.Domain/Entities/Camera.cs), [`Person` et `KnownFace`](../src/Heimdall.Domain/Entities/Person.cs), [`Vehicle`](../src/Heimdall.Domain/Entities/Vehicle.cs), [`CameraEvent`](../src/Heimdall.Domain/Entities/CameraEvent.cs).
|
||||
|
||||
---
|
||||
|
||||
@@ -115,10 +106,10 @@ Enum: GpuAcceleration, ThemeMode
|
||||
|
||||
## Authentification — `docs/auth-roles.md`
|
||||
|
||||
- 2 types d'utilisateurs : Admin (tout) + User (N sites)
|
||||
- 3 rôles : Admin, Supervisor et Viewer; les permissions viennent du rôle et l'accès aux sites/caméras est vérifié séparément selon la ressource
|
||||
- ASP.NET Core Identity + JWT + Refresh tokens
|
||||
- Permissions par Policy : Camera.Read, Admin.Manage...
|
||||
- Scope site : un User ne voit que ses sites assignés
|
||||
- Accès aux ressources : les services d’accès vérifient le périmètre site/caméra pour chaque opération; voir `docs/auth-roles.md`
|
||||
- Visibilité UI adaptée au rôle (menus, boutons)
|
||||
- Voir `docs/auth-roles.md` pour le détail complet
|
||||
|
||||
@@ -126,30 +117,42 @@ Enum: GpuAcceleration, ThemeMode
|
||||
|
||||
- ONVIF WS-Discovery (même VLAN) + discovery manuelle (IP)
|
||||
- Protocole Imou : activation RTSP manuelle requise
|
||||
- FFmpeg capture : RTSP → H264, GPU auto-détection (NVENC/QSV/VAAPI/CPU)
|
||||
- AI Pipeline : Agent CPU (YOLOv8 nano) → analyse IA sur agents GPU (ONNX Runtime, local ou via broker inter-sites)
|
||||
- Analyse d'images : YOLO/ONNX sur Agent, CPU par défaut; CUDA NVIDIA optionnel avec fallback CPU. Les détections de matériel AMD/Intel alimentent l'inventaire et ne prouvent pas une inférence accélérée.
|
||||
- Mode d'analyse distant : configurable avec un broker et repli local si celui-ci est inaccessible; aucun déploiement inter-sites n'est validé par cette configuration seule.
|
||||
- Détection : objets, visages, plaques (LPR), véhicules
|
||||
- Stockage credentials caméras chiffré (IDataProtector)
|
||||
|
||||
## Streaming live — `docs/signalr-usage.md`
|
||||
## Streaming live — parcours logiciel livré, validation externe partielle
|
||||
|
||||
- WebRTC P2P via SIPSorcery (latence < 500ms)
|
||||
- Signaling via SignalR hub /hubs/streaming (SDP + ICE)
|
||||
- SFU (MediaMTX) pour multi-utilisateurs (>2 viewers)
|
||||
- Blazor Server + JS module autonome pour <video>
|
||||
- Voir `docs/signalr-usage.md` §3 pour le protocole complet
|
||||
Le parcours actuel utilise le relay Agent→MediaMTX en RTSP(S), puis WHEP/WebRTC
|
||||
entre le navigateur et MediaMTX. Central fournit des sessions courtes et autorise
|
||||
les lectures selon les droits sur la caméra; SignalR ne transporte pas le média
|
||||
ni le signaling SDP/ICE de ce parcours. L’application n’expose pas de hub
|
||||
`/hubs/streaming`. Les URL et ICE servers dépendent de la configuration de
|
||||
l’installation. La négociation synthétique dispose d’une preuve séparée, mais
|
||||
cela ne valide ni une caméra physique, ni l’accès depuis un réseau externe, ni
|
||||
une latence cible en déploiement; voir #161 et #341.
|
||||
|
||||
Le relay compare la source RTSP effective (sous-flux s’il est configuré, sinon
|
||||
flux principal) et redémarre le processus après un changement de source pour le
|
||||
même CameraId. Ce comportement est couvert par les tests Agent et l’acceptance
|
||||
locale de #355; aucune caméra réelle ni réseau externe n’a été validé.
|
||||
|
||||
## Temps réel (SignalR) — `docs/signalr-usage.md`
|
||||
|
||||
Résumé des cinq hubs actuellement mappés :
|
||||
|
||||
| Hub | Route | Usage |
|
||||
|---|---|---|
|
||||
| Config | `/hubs/config` | Configuration et commandes Agent |
|
||||
| Events | `/hubs/events` | Événements détection temps réel |
|
||||
| Streaming | `/hubs/streaming` | Signaling WebRTC |
|
||||
| Monitoring | `/hubs/monitoring` | Status agents, caméras |
|
||||
| Notifications | `/hubs/notifications` | Notifications in-app |
|
||||
| Admin | `/hubs/admin` | Broadcast changements config |
|
||||
|
||||
Voir `docs/signalr-usage.md` pour tous les events, groupes, code.
|
||||
Voir [`docs/signalr-usage.md`](signalr-usage.md) pour les méthodes invocables,
|
||||
messages émis et contrôles d’accès. Ce résumé ne reproduit ni le code ni toutes
|
||||
les clés de groupe internes.
|
||||
|
||||
## Jobs planifiés (Hangfire) — `docs/hangfire-usage.md`
|
||||
|
||||
@@ -162,17 +165,18 @@ Voir `docs/hangfire-usage.md` pour le code complet de chaque job.
|
||||
|
||||
## Notifications — `docs/notifications.md`
|
||||
|
||||
- Email SMTP (FluentEmail), Gotify push
|
||||
- Templates Markdown avec Scriban, variables, fallback i18n
|
||||
- Templates éditables depuis l'UI Admin
|
||||
- File Hangfire avec retry (3 tentatives)
|
||||
- Résumés quotidiens/hebdomadaires planifiés
|
||||
- Voir `docs/notifications.md` pour le détail complet
|
||||
Les notifications in-app sont consultables dans `/notifications`. Les canaux
|
||||
externes livrés sont l’email SMTP et ntfy; les administrateurs configurent et
|
||||
testent ces services dans `/settings`, tandis que les préférences individuelles
|
||||
et les options de résumé se règlent dans `/profile`. Les digests quotidien et
|
||||
hebdomadaire sont planifiés par les jobs Hangfire actuels. Voir
|
||||
[`docs/notifications.md`](notifications.md) pour les endpoints, les contrôles
|
||||
d’accès, la cadence et les limites de validation SMTP/ntfy.
|
||||
|
||||
## Stockage & Rétention — `docs/hangfire-usage.md`
|
||||
|
||||
- RustFS (par défaut), S3-compatible (AWS S3, MinIO), Local (fallback)
|
||||
- L'Agent écrit les segments directement sur S3
|
||||
- L'Agent découpe le flux RTSP principal en segments MP4 dans son spool local, puis envoie les segments terminés au Central via l'API; le Central les écrit dans le fournisseur de stockage configuré
|
||||
- Retention configurable par caméra (7-90 jours)
|
||||
- Hangfire purge les fichiers expirés
|
||||
- Voir `docs/hangfire-usage.md` §2 pour les jobs
|
||||
@@ -180,15 +184,18 @@ Voir `docs/hangfire-usage.md` pour le code complet de chaque job.
|
||||
## Interface Web (Blazor) — `docs/ui-pages.md`
|
||||
|
||||
- MudBlazor, Interactive Server Rendering
|
||||
- 8 pages : Login, Dashboard, Sites, Cameras, Persons, Events, Admin, Alertes
|
||||
- Live vidéo via module JS autonome (WebRTC)
|
||||
- Parcours documentés : authentification, dashboard, sites/caméras, personnes,
|
||||
événements, alertes/notifications, profil et administration. Les routes et
|
||||
pages détaillées sont recensées dans [`docs/ui-pages.md`](ui-pages.md);
|
||||
l’administration est répartie entre pages protégées et ne correspond pas à
|
||||
une route unique `/admin`.
|
||||
- Live vidéo depuis le détail caméra : publication RTSP Agent→MediaMTX et lecture WHEP/WebRTC via `live-view.js`
|
||||
- Thème Light/Dark/Auto, localisation française
|
||||
- Voir `docs/ui-pages.md` pour les maquettes ASCII complètes
|
||||
|
||||
## Application web installable — PWA
|
||||
|
||||
Le client natif est retiré. La cible est le serveur Blazor accessible sur mobile et installable depuis le navigateur.
|
||||
Installation, page hors connexion, reprise de session et Web Push doivent être implémentés ; le rendu Interactive Server nécessite une connexion pour les fonctions métier.
|
||||
Le client natif est retiré. Le socle PWA livré comprend le manifeste, le service worker borné et la page d’information hors connexion. Les écrans métier restent dépendants d’une connexion Interactive Server; Web Push et consultation métier hors ligne ne sont pas implémentés. Les validations appareils/déploiement restent à faire.
|
||||
Voir [l’audit et le plan PWA](pwa.md) pour les écarts, critères de réception et l’option de consultation hors ligne ultérieure.
|
||||
|
||||
---
|
||||
@@ -202,31 +209,26 @@ services:
|
||||
heimdall-api: # ASP.NET Core API + SignalR
|
||||
heimdall-web: # Blazor Web App (MudBlazor)
|
||||
heimdall-worker: # Hangfire jobs (PostgreSQL)
|
||||
heimdall-agent: # SIPSorcery + FFmpeg (InMemory Hangfire)
|
||||
heimdall-agent: # Agent .NET + FFmpeg relay (Hangfire InMemory)
|
||||
postgresql: # Base de données
|
||||
rustfs: # Stockage S3 (enregistrements)
|
||||
# IA lourde (détection, visages, LPR) : agents GPU ONNX Runtime — pas de service central
|
||||
ollama: # LLM local (résumés)
|
||||
mediamtx: # SFU WebRTC (optionnel, multi-user)
|
||||
# Analyse ONNX exécutée par l'Agent (CPU par défaut, CUDA NVIDIA optionnel); voir docs/gpu-runtime.md
|
||||
ollama: # service optionnel; URL configurable et disponibilité sondée, aucune génération LLM livrée
|
||||
mediamtx: # Serveur média RTSP/WHEP (optionnel, live vidéo)
|
||||
coturn: # TURN relay (optionnel, double NAT)
|
||||
```
|
||||
|
||||
## GPU Passthrough
|
||||
## GPU et inférence
|
||||
|
||||
| Conteneur | GPU | Docker |
|
||||
|---|---|---|
|
||||
| `heimdall-agent` (GPU) | NVIDIA/AMD/Intel | profiles compose GPU : nvidia / rocm (/dev/kfd,/dev/dri) / vaapi (/dev/dri) |
|
||||
| `heimdall-agent` | NVIDIA/Intel/AMD | `--gpus all` ou `--device /dev/dri:/dev/dri` |
|
||||
| `ollama` | NVIDIA (opt) | `--gpus all` |
|
||||
|
||||
Auto-détection GPU par l'Agent au démarrage (NVENC > QSV > VAAPI > CPU).
|
||||
|
||||
## Estimation capacité CPU (Intel i5-10gen)
|
||||
|
||||
| Mode | 720p | 1080p | 4K |
|
||||
|---|---|---|---|
|
||||
| CPU (libx264) | 8 flux | 4 flux | 1 flux |
|
||||
| GPU (NVENC/QSV) | 20+ flux | 12+ flux | 4+ flux |
|
||||
L'image et le chemin Agent par défaut utilisent `CPUExecutionProvider`. Une
|
||||
image amd64 NVIDIA/CUDA signée est proposée en option; si CUDA ne peut pas
|
||||
initialiser une session, l'Agent revient au CPU. L'inventaire peut détecter du
|
||||
matériel NVIDIA, AMD et Intel, mais les overlays AMD/Intel ne fournissent pas
|
||||
de backend ONNX correspondant. La détection de capacités d'encodage dans
|
||||
l'inventaire n'implique pas leur utilisation par les parcours vidéo. Voir
|
||||
[`docs/gpu-runtime.md`](gpu-runtime.md) pour les variantes et les preuves
|
||||
disponibles. L'exécution CUDA sur matériel réel et les performances par flux
|
||||
restent à mesurer; aucune capacité chiffrée n'est annoncée ici.
|
||||
|
||||
---
|
||||
|
||||
@@ -236,7 +238,7 @@ Auto-détection GPU par l'Agent au démarrage (NVENC > QSV > VAAPI > CPU).
|
||||
- Serilog (structure logging)
|
||||
- OpenTelemetry ready
|
||||
- Sentry SDK compatible GlitchTip
|
||||
- Healthchecks (API, Agent, DB, RustFS, Broker IA, Ollama)
|
||||
- Health checks Central : `/healthz` est une liveness toujours `200`; `/readyz` vérifie PostgreSQL et le stockage actif (`200` si healthy, sinon `503`); `/health/live` vérifie PostgreSQL plus le backend IA configuré (CodeProject.AI ou Ollama; l'absence de backend IA est valide) et renvoie `503` si un check n'est pas healthy. Côté Agent, `/healthz` agrège `agent_health` et `live` (`Degraded` → `200`, `Unhealthy` → `503`); `/health/live` expose la dégradation du pipeline IA (`200` healthy, sinon `503`). Aucun health check Central distinct du broker distant n'est enregistré; voir [`HealthController`](../src/Heimdall.Web/Controllers/HealthController.cs), [`AiHealthCheck`](../src/Heimdall.Infrastructure/HealthChecks/AiHealthCheck.cs) et [`Agent Program`](../src/Heimdall.Agent/Program.cs).
|
||||
- Tests : xUnit + Shouldly + NSubstitute + bUnit + Testcontainers
|
||||
|
||||
---
|
||||
|
||||
+34
-64
@@ -297,41 +297,37 @@ Docker Compose affiche le YAML comme une étape « Configuration », suivie des
|
||||
|
||||
## P4 — Caméras
|
||||
|
||||
### Live View — P4a (DERNIÈRE page implémentée)
|
||||
### Live view — lecteur intégré au détail caméra (parcours logiciel livré)
|
||||
|
||||
**Route** : `/cameras/{id}/live`
|
||||
**Auth** : Requise
|
||||
**Route** : `/cameras/{id}` (page détail, section Live)
|
||||
**Auth** : session utilisateur requise; l’API vérifie aussi l’accès à la caméra
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ 📷 Entrée — Live [Plein écran]│
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────────────┐ │
|
||||
│ │ │ │
|
||||
│ │ FLUX VIDÉO WEBRTC │ │
|
||||
│ │ │ │
|
||||
│ │ <video> élément HTML natif │ │
|
||||
│ │ │ │
|
||||
│ │ ⏳ Loading... | 🟢 Live | 🔴 Offline │ │
|
||||
│ │ │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Qualité: [1080p ▼] [📷 Snapshot] [⏺️ Enregistrer]│
|
||||
│ │
|
||||
│ ┌───Événements récents (cette caméra)────────────┐ │
|
||||
│ │ 🟢 14:23 — Personne détectée │ │
|
||||
│ │ 🟡 14:20 — Véhicule détecté │ │
|
||||
│ └────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Timeline: [══════■══════■══════════■══════] │
|
||||
│ 14:00 14:10 14:20 14:30 Maintenant │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
┌────────────────────────────────────────────────────┐
|
||||
│ Live [Regarder le direct] │
|
||||
│ ┌──────────────────────────────────────────────┐ │
|
||||
│ │ <video> HTML natif, autoplay, playsinline │ │
|
||||
│ │ lecture navigateur via WHEP/WebRTC │ │
|
||||
│ └──────────────────────────────────────────────┘ │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Attention Blazor Server + WebRTC** : Voir §26 de la spec — le flux WebRTC
|
||||
est géré par un module JS autonome (`wwwroot/js/liveView.js`) qui survit
|
||||
aux reconnexions Blazor. Le `<video>` est un élément HTML standard,
|
||||
pas un composant Blazor.
|
||||
Le bouton est désactivé lorsque l’état caméra n’est pas `Online`; il démarre ou
|
||||
arrête le lecteur. Le composant importe `wwwroot/js/live-view.js`, demande une
|
||||
session de lecture à `POST /api/live-media/cameras/{cameraId}/session`, puis
|
||||
négocie WHEP avec l’URL et le jeton temporaires retournés par Central. L’Agent
|
||||
publie le flux caméra vers MediaMTX en RTSP(S). À l’arrêt ou à la destruction du
|
||||
composant, le client ferme la connexion WebRTC et libère la session.
|
||||
|
||||
La route WHEP, les ICE servers et les paramètres de publication dépendent de la
|
||||
configuration Central/MediaMTX. Une recette avec média synthétique prouve le
|
||||
parcours logiciel seulement; elle ne prouve pas l’accès d’une caméra physique,
|
||||
le TURN depuis Internet ni un budget de latence en exploitation (voir #161 et
|
||||
#341). La maquette ci-dessus représente le lecteur livré; le choix de qualité,
|
||||
l’enregistrement depuis le lecteur et une timeline de lecture ne sont pas des
|
||||
contrôles présents dans ce panneau. Changer l’URL RTSP d’une caméra tout en
|
||||
gardant le même ID et la même assignation peut laisser l’ancien relay actif
|
||||
jusqu’au renouvellement de sa session; cette limite Agent est suivie dans #355.
|
||||
|
||||
### Détail Caméra — P4b
|
||||
|
||||
@@ -566,41 +562,15 @@ Matrice complète des 15 permissions système avec coches par rôle
|
||||
|
||||
---
|
||||
|
||||
## P14 — Administration (legacy)
|
||||
## P14 — Administration centralisée (ancienne maquette retirée)
|
||||
|
||||
**Route** : `/admin`
|
||||
**Auth** : Requise + `Admin.Manage`
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ Administration │
|
||||
│ │
|
||||
│ ┌──── Tabs ───────────────────────────────────────┐ │
|
||||
│ │ Utilisateurs | Rôles | Clés API | Jobs │ │
|
||||
│ │ │ │
|
||||
│ │ [Tab Utilisateurs] │ │
|
||||
│ │ ┌──────────────────────────────────────────────┐ │ │
|
||||
│ │ │ Jean Dupont Admin jean@ex.com [×] │ │ │
|
||||
│ │ │ Marie Martin Superviseur marie@ex.com [×] │ │ │
|
||||
│ │ │ Paul View paul@ex.com [×] │ │ │
|
||||
│ │ └──────────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ [Tab Clés API] │ │
|
||||
│ │ ┌──────────────────────────────────────────────┐ │ │
|
||||
│ │ │ Key-1 Camera.Read 01/01/2026 Actif [×] │ │ │
|
||||
│ │ │ Key-2 Camera.Write 15/06/2026 Expiré [×] │ │ │
|
||||
│ │ │ Key-3 Person.Read 01/07/2026 Actif [×] │ │ │
|
||||
│ │ └──────────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ [Tab Jobs Hangfire] │ │
|
||||
│ │ ┌──────────────────────────────────────────────┐ │ │
|
||||
│ │ │ Retention Check Tous les jours 🟢 OK │ │ │
|
||||
│ │ │ S3 Cleanup Tous les jours 🟢 OK │ │ │
|
||||
│ │ │ Unknown Faces Clean Toutes les sem. 🟢 OK │ │ │
|
||||
│ │ └──────────────────────────────────────────────┘ │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
La page d’accueil `/admin` et les onglets regroupés dans cette maquette ne sont
|
||||
pas mappés dans le runtime. Les capacités d’administration sont réparties sur
|
||||
les pages actuelles : `/users`, `/admin/roles`, `/admin/groups`,
|
||||
`/admin/claims`, `/admin/agents`, `/admin/api-keys`, `/settings` et `/hangfire`.
|
||||
Les notifications et la configuration des releases sont des sections de
|
||||
`/settings`, pas des sous-pages d’un dashboard `/admin`. Voir
|
||||
[`docs/auth-roles.md`](auth-roles.md) pour les rôles, routes et policies actuels.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
|
||||
- `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.
|
||||
- Preserve the entire Data Protection ring and `dp-cert.pfx` together. Expired keys can still be required to unprotect stored payloads; never replace/delete one file as part of a restore. Heimdall has no validated manual rotation process for the certificate that protects the ring at rest; keep certificate rotation separate until tested against existing payloads. See `docker/backup/README.md`.
|
||||
- PostgreSQL and protected-volume archives are separate snapshots. The application does not coordinate them into one atomic point in time.
|
||||
- The scheduled backup Compose installs Alpine `aws-cli`, `bash`, and GNU `coreutils`; it does not install MinIO Client (`mc`). `backup-rustfs.sh` uses `aws s3 sync` in this shipped container and only selects `mc mirror` when `mc` is already present in a customized environment. Keep `docker/backup/README.md` aligned with this effective default and never document a retired `mc` download as an installer step.
|
||||
- The scheduled Compose sets `TZ` to `Europe/Paris` by default. Cron times in `docker-compose.backup.yml` use the container timezone, while scripts use UTC for archive timestamps and retention cutoffs. Document both clocks separately and describe any changed `TZ` as an operator configuration, not as UTC scheduling.
|
||||
- `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
|
||||
@@ -24,7 +26,7 @@ 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. For actual RPO/RTO drills, use the timestamp, resource, host, and repeated-run procedure in `docker/backup/README.md` and record the operator-approved target separately.
|
||||
5. Install an EXIT cleanup trap before build/start. Tear down only the disposable project with `docker compose -p <name> 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.
|
||||
6. The scheduled backup image installs Alpine's `aws-cli`, `bash`, and GNU `coreutils` (`date -d` retention cutoffs do not work in BusyBox), not MinIO Client. `backup-rustfs.sh` therefore uses `aws s3 sync`; its `mc mirror` branch is only a fallback when a customized image already provides `mc`. Do not rely on the retired MinIO client download URL. The AWS CLI path passes configured S3 credentials explicitly 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.
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ description: Implement and validate Heimdall user-to-camera grants and group cam
|
||||
|
||||
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.
|
||||
|
||||
When editing authorization examples in `docs/auth-roles.md`, verify routes against the actual controller mappings and explain the query/service-level access filtering. Human JWTs carry role/permission and session claims, not a frozen list of site IDs; do not describe a global `SiteScopeMiddleware` unless one is implemented.
|
||||
|
||||
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:
|
||||
|
||||
@@ -5,13 +5,11 @@ description: Build and acceptance-test Heimdall changes in a disposable Docker C
|
||||
|
||||
# Disposable Compose acceptance
|
||||
|
||||
Follow the shared [disposable test environment skill](/home/nonobis/skills/skills/disposable-test-environment/SKILL.md) for general isolation and cleanup policy. This skill specifies the additional exact Compose contract for Heimdall and remains mandatory for behavior, deployment, and operational changes.
|
||||
|
||||
Follow [Infisical secrets](../infisical-secrets/SKILL.md) when the surrounding task also needs real credentials. Acceptance projects must always use generated synthetic values and must never retrieve deployment secrets from Infisical.
|
||||
|
||||
Use this skill for every Heimdall behavior, deployment, or operational change. Read the relevant project skill too; for first administrator setup, use `first-admin-bootstrap`.
|
||||
|
||||
When implementation or acceptance preparation has independent branches, use [parallel development with Orca](../parallel-development/SKILL.md) to assign bounded work. Keep the final Compose run, cleanup verification, and acceptance evidence under one coordinator so the combined change is validated as a whole.
|
||||
|
||||
Track the change and its acceptance evidence in a Gitea issue; follow [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md). Put the project name, exact local image tags and cleanup verification in the issue or linked PR, and close the ticket only after the recipe and other required gates pass.
|
||||
Read the relevant product acceptance skill too; for first administrator setup, use `first-admin-bootstrap`.
|
||||
|
||||
## Safety and isolation
|
||||
|
||||
|
||||
@@ -9,10 +9,15 @@ Read `AGENTS.md`, the linked Gitea issue, `docs/docker-compose.md`, and the rele
|
||||
|
||||
## Project-specific documentation checks
|
||||
|
||||
- Treat `docs/implementation.md` as a July 2026 historical MVP archive in its entirety. Do not use its old phase statuses, paths, commands, endpoint tables, or counts as current guidance; direct readers to the current focused docs and use Gitea issues for live status.
|
||||
- When changing document structure, section numbering, or a product status summarized in `docs/specs.md`, verify the entry points in `docs/README.md`: every section/document reference must resolve, and summary wording must preserve optional, partial, and externally unvalidated states.
|
||||
- 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.
|
||||
- Recording status must be traced across `AgentRecordingService` (primary RTSP stream, local MP4 segment spool, Central API upload), `RecordingsController`/Application storage, and the camera detail playback UI. Do not say recording is missing or that the Agent writes directly to S3; distinguish implemented code from real-camera/deployment validation.
|
||||
- Live relay source tracking uses `AgentCameraConfig.EffectiveRtspUrl` (configured substream, otherwise primary RTSP). After a source change, `LiveCameraRelayService` stops and disposes the old FFmpeg process before starting the new source; do not retain the former renewal-delay caveat after issue #355.
|
||||
- The current PWA baseline includes a manifest, bounded service worker, and static offline page. Web Push backend/client and offline business screens are not implemented; use `docs/pwa.md` for device and deployment validation status.
|
||||
- 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.
|
||||
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
---
|
||||
name: ef-core-persistence
|
||||
description: Implement or review database persistence in Heimdall with Entity Framework Core, including SQLite Agent stores and PostgreSQL behavior.
|
||||
description: Preserve Heimdall's PostgreSQL Central and SQLite Agent persistence profiles, migration compatibility, and local CI policy.
|
||||
---
|
||||
|
||||
# Heimdall EF Core persistence
|
||||
# Heimdall persistence profile
|
||||
|
||||
Use this skill whenever changing how application or Agent data is read or written.
|
||||
Apply the shared [dotnet-engineering skill](/home/nonobis/skills/skills/dotnet-engineering/SKILL.md) for EF Core design, query specifications, lifecycle, raw SQL exceptions, and relational verification. Apply the shared [Gitea delivery workflow](/home/nonobis/skills/skills/gitea-delivery-workflow/SKILL.md) for issue evidence and release/PR lifecycle. This file contains only provider and repository-specific requirements.
|
||||
|
||||
For work spanning multiple persistence concerns, use [parallel development with Orca](../parallel-development/SKILL.md). Keep each `DbContext` operation isolated; assign migration/model ownership clearly and serialize edits that touch the same entity configuration or migration chain.
|
||||
## Providers and ownership
|
||||
|
||||
- Use EF Core LINQ and entity configurations for CRUD. Prefer projections, bounded result sets, asynchronous APIs, and `CancellationToken`; use `AsNoTracking` for read-only entity queries.
|
||||
- Create a short-lived `DbContext` per operation. Hosted services and concurrent workers should use `IDbContextFactory<TContext>` and dispose each context; never share a context across parallel work.
|
||||
- Evolve schemas through reviewed EF Core migrations. Preserve deployed data and test upgrades from every supported on-disk schema, including Agent-local SQLite outboxes.
|
||||
- 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.
|
||||
- Central persistence uses EF Core with PostgreSQL and lives in `Heimdall.Infrastructure`.
|
||||
- Agent local durable data and camera discovery use SQLite. Keep their schema lifetimes and upgrade paths distinct from Central's PostgreSQL migrations.
|
||||
|
||||
Before editing, inspect this repository's `AGENTS.md`, the linked Gitea issue, model configuration, latest migration, and callers. After editing, run the relevant suite and CI persistence policy check, then update the issue with evidence and remaining deployment checks.
|
||||
## Schema evolution
|
||||
|
||||
## Microsoft references
|
||||
- Central's EF Core migration chain and model snapshot live under `src/Heimdall.Infrastructure/Migrations/`. Validate schema compatibility against PostgreSQL.
|
||||
- Agent outbox and camera-discovery SQLite stores have separate local schema histories; retain existing on-disk data when upgrading those schemas.
|
||||
- Moving Identity model classes without changing existing tables requires the explicit empty migration and snapshot update described in [Heimdall identity](../heimdall-identity/SKILL.md); verify PostgreSQL compatibility before delivery.
|
||||
- Startup migration retries and fail-closed health behavior are defined by [database migration startup](../database-migration-startup/SKILL.md).
|
||||
|
||||
- [EF Core efficient querying](https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying)
|
||||
- [EF Core tracking and no-tracking](https://learn.microsoft.com/en-us/ef/core/querying/tracking)
|
||||
- [EF Core raw SQL queries](https://learn.microsoft.com/en-us/ef/core/querying/sql-queries)
|
||||
- [EF Core migrations](https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/)
|
||||
- [SQLite provider for EF Core](https://learn.microsoft.com/en-us/ef/core/providers/sqlite/)
|
||||
## Repository enforcement and exceptions
|
||||
|
||||
- `scripts/ci/check-efcore-usage.py` enforces the production persistence boundary. Production reads/writes use EF Core; direct ADO.NET/provider commands are prohibited. The allowlist is limited to documented provider capabilities with no portable EF equivalent and to migration/test setup cases explicitly accepted by the repository policy.
|
||||
- For a new allowlisted production exception, document the exact source path and capability in `EF_CORE_EXCEPTIONS`, put an adjacent `EF Core exception:` rationale in source, and add the relational behavior test required by the shared skill and CI policy.
|
||||
- Keep provider-specific EF operations in Infrastructure or a dedicated adapter. Do not move PostgreSQL or SQLite implementation details into Domain or Application.
|
||||
|
||||
Use the focused [database migration startup acceptance](../database-migration-startup/SKILL.md) for startup behavior and the relevant product/Compose recipe for behavior changes. Report which provider and existing schema were exercised; a PostgreSQL result does not establish SQLite compatibility, or vice versa.
|
||||
@@ -1,97 +1,33 @@
|
||||
---
|
||||
name: gitea-ticket-workflow
|
||||
description: Create, maintain, link, and close Heimdall project tickets in Gitea as the sole work tracking system.
|
||||
description: Preserve Heimdall's Gitea labels and issue-template fields within the shared Gitea delivery lifecycle.
|
||||
---
|
||||
|
||||
# Gitea ticket workflow
|
||||
# Heimdall Gitea profile
|
||||
|
||||
For credentials used while investigating or validating tickets, follow [Infisical secrets](../infisical-secrets/SKILL.md). Never put secret values in issue descriptions or comments; use metadata-only existence checks when documenting prerequisites.
|
||||
Follow the shared [Gitea delivery workflow](/home/nonobis/skills/skills/gitea-delivery-workflow/SKILL.md) for intake, deduplication, issue evidence, PR linking, release and closure. Follow shared [backlog maintenance](/home/nonobis/skills/skills/backlog-maintenance/SKILL.md), [Gitea authentication](/home/nonobis/skills/skills/gitea-auth/SKILL.md), and [work intake](/home/nonobis/skills/skills/work-intake/SKILL.md) where applicable. Gitea project issues remain Heimdall's only durable backlog; do not add a Markdown backlog.
|
||||
|
||||
When a change is delivered through a PR, include its automatic release assessment using [pull request release assessment](../pr-release-versioning/SKILL.md); do not ask the user to choose whether or which version to release.
|
||||
## Repository labels
|
||||
|
||||
Gitea issues are the source of truth for planned work, acceptance evidence, operational follow-up, and completion. Do not use a repository markdown checklist as a parallel backlog.
|
||||
Use the shared workflow's type/priority/domain and conditional validation label rules with Heimdall's existing label vocabulary. As of 2026-11-16, the repository labels are:
|
||||
|
||||
For implementation work that has independent tasks, use [parallel development with Orca](../parallel-development/SKILL.md). Keep Gitea as the work-status source: create linked issues for independently deliverable outcomes, while Orca Runs/Tasks coordinate the execution and dependencies.
|
||||
| Group | Existing labels |
|
||||
|---|---|
|
||||
| Type | `type:feature`, `type:bug`, `type:maintenance`, `type:docs`, `type:security` |
|
||||
| Priority | `priority:P0`, `priority:P1`, `priority:P2`, `priority:P3` |
|
||||
| Domain | `area:ci`, `area:release`, `area:install`, `area:agent`, `area:camera`, `area:analysis`, `area:storage`, `area:notifications`, `area:auth`, `area:ui`, `area:monitoring`, `area:docs` |
|
||||
| Validation | `validation:field`, `validation:deployment`, `validation:hardware`, `validation:backup-restore` |
|
||||
| Temporary marker | `blocked`, `needs-design`, `needs-decision` |
|
||||
|
||||
## Before implementation
|
||||
The Gitea issue templates provide the project-specific fields below. Template frontmatter sets the type label only; add the priority and domain labels when creating the issue. Keep the template fields and this label vocabulary aligned with the labels actually present in Gitea.
|
||||
|
||||
1. Read `AGENTS.md` and the focused skill(s) for the affected area.
|
||||
2. Identify the repository from `git remote get-url origin`; use the configured Gitea API/CLI credentials without printing them. Never put tokens in URLs, command output, issue text, or PR descriptions.
|
||||
3. Search open and closed issues for the topic, identifiers, PRs, and acceptance gaps. Reuse the matching issue: reopen it when required work remains, or add a clearly scoped follow-up issue when the old issue is closed and represents a completed unit.
|
||||
4. Create one issue per independently deliverable behavior or operational validation. An issue must include:
|
||||
- a concise, outcome-oriented title and relevant component/priority labels;
|
||||
- a plain-language summary explaining the user/operator impact and why the work matters;
|
||||
- a short current-state section separating implemented behavior, local evidence, CI evidence, and real deployment/hardware evidence;
|
||||
- an analysis of the actual gap: what fails or is missing, what evidence proves it, likely causes where known, and what remains uncertain;
|
||||
- scope and explicit out-of-scope items, dependencies, risks, assumptions, and the expected owner/environment for external checks;
|
||||
- numbered implementation/validation steps in dependency order, including safe test data, observable outcomes, and cleanup;
|
||||
- independently checkable acceptance criteria, with no generic placeholder criteria;
|
||||
- relevant files, prior issue/PR/run links, and the focused skill.
|
||||
5. Apply the ticket labels described in **Ticket labels** below before handing the issue to implementation. Labels are metadata for filtering and triage; they do not replace the title, scope, or acceptance criteria.
|
||||
6. For UI/product work, decide whether a mockup materially clarifies the acceptance criteria. If needed, attach a mockup or link to a Penpot/Figma artifact; state the viewport, states, responsive breakpoints, and interactions it must cover. Do not block infrastructure work on an unnecessary mockup.
|
||||
7. Confirm the created/updated issue through the API and record its canonical URL/number in the branch/PR context.
|
||||
## Issue-template fields
|
||||
|
||||
## Ticket labels
|
||||
- **Bug** (`.gitea/ISSUE_TEMPLATE/bug.md`): context, observed behavior, expected behavior, reproduction, specification reference, impact, proposed fix, and definition of done.
|
||||
- **Feature** (`.gitea/ISSUE_TEMPLATE/feature.md`): context, specification reference, expected behavior, current state, proposed decomposition, measurable acceptance criteria, likely files, and definition of done.
|
||||
- **Maintenance** (`.gitea/ISSUE_TEMPLATE/chore.md`): context, task, deliverables, verification, and definition of done.
|
||||
- **Technical debt** (`.gitea/ISSUE_TEMPLATE/tech-debt.md`): context, debt description, impact, proposed correction, specification reference, and definition of done.
|
||||
|
||||
Every issue should have, at minimum, one **type** label, one **priority** label, and one **domain** label. Add a **validation** label when the ticket is mainly about an acceptance/deployment check. Apply existing repository labels through the Gitea issue API or UI; if a required label is missing, create it once with a clear description and reuse it rather than inventing synonyms.
|
||||
For all types, include the shared workflow's current evidence, gap, scope/exclusions, dependencies, ordered validation/cleanup, acceptance owner, and links in the relevant fields. UI acceptance that depends on layout or interactions follows the shared mockup guidance; use Penpot when the issue requires a Heimdall UI design artifact.
|
||||
|
||||
Use this vocabulary consistently:
|
||||
|
||||
| Group | Labels | Use |
|
||||
|---|---|---|
|
||||
| Type | `type:feature`, `type:bug`, `type:maintenance`, `type:docs`, `type:security` | Main nature of the work; select one. |
|
||||
| Priority | `priority:P0`, `priority:P1`, `priority:P2`, `priority:P3` | `P0` blocks release/security or causes an active outage; `P1` is important for the current release or core journey; `P2` is normal planned work; `P3` is low urgency. Select one and state why in the issue if not obvious. |
|
||||
| Domain | `area:ci`, `area:release`, `area:install`, `area:agent`, `area:camera`, `area:analysis`, `area:storage`, `area:notifications`, `area:auth`, `area:ui`, `area:monitoring`, `area:docs` | Main owning subsystem; use multiple only when work genuinely crosses boundaries. |
|
||||
| Validation | `validation:field`, `validation:deployment`, `validation:hardware`, `validation:backup-restore` | Add when closure depends on the corresponding real environment or external evidence. Do not apply to ordinary code-only acceptance. |
|
||||
| State marker | `blocked`, `needs-design`, `needs-decision` | Add only while the named condition is true; remove it when resolved. Explain the blocker/decision in the issue body. |
|
||||
|
||||
Before creating a label, search all repository labels and use an existing equivalent. Keep labels lowercase except the conventional priority spelling above. Do not create status labels such as `open`, `closed`, `in progress`, or `done`; Gitea issue state and assignee/project workflow own those concepts. Do not use labels to encode dynamic details such as a PR number, release version, user, camera, or site.
|
||||
|
||||
On backlog review, correct missing or stale labels when the scope changes. When splitting an issue, label each child for its own type, priority, domain, and validation requirement; do not blindly copy every parent label. A label change alone does not satisfy acceptance criteria or close the ticket.
|
||||
|
||||
## During implementation
|
||||
|
||||
- Keep the issue current with material discoveries, decisions, blockers, and validation evidence. Do not duplicate long-lived status in a local markdown backlog.
|
||||
- Reference the issue in branch and commit context where useful. Every PR body must link the issue with `Closes #N` when merge should close it, or `Refs #N` when the issue tracks work that remains after this PR.
|
||||
- A PR touching a subset of a larger ticket must say exactly which acceptance criteria it satisfies and which remain open. Split follow-up tickets when the remaining work is independently actionable.
|
||||
- Keep project-specific implementation and acceptance procedures in `skills/`; link the relevant skill from the issue and PR.
|
||||
- For external validation, create/update a focused ticket with owner, prerequisites, safe test data, procedure, expected evidence, and cleanup. Never mark an external integration validated based on mocks or configuration presence.
|
||||
|
||||
## Mockups and attachments
|
||||
|
||||
- Attach a mockup when layout, hierarchy, responsive behavior, or interaction flow is a substantial part of acceptance. Prefer an existing project design artifact; otherwise create a focused Penpot/Figma frame and attach/link it from the issue.
|
||||
- The issue describes what the mockup demonstrates and its status (proposed/approved/superseded). Keep source design links and exported images free of secrets or real customer data.
|
||||
- API, persistence, CI, and maintenance tickets generally need no mockup; state that only when ambiguity might otherwise cause delay.
|
||||
|
||||
## Human-readable issue layout
|
||||
|
||||
Use this order and keep each section focused:
|
||||
|
||||
1. **Résumé** — one or two sentences describing the intended result.
|
||||
2. **Pourquoi** — user/operator impact and the reason for prioritizing the work.
|
||||
3. **État actuel et preuves** — what is already implemented and exactly what tests/runs prove; distinguish synthetic/local/CI/production evidence.
|
||||
4. **Écart à résoudre** — the remaining failure or uncertainty in concrete terms; avoid starting with a fragment copied from a longer checklist sentence.
|
||||
5. **Analyse** — known cause, constraints, failure modes, security/data impact, assumptions, and unanswered decisions.
|
||||
6. **Plan de travail** — ordered steps with dependencies and observable outputs. Split independent work into linked child issues instead of making one ticket cover unrelated deliverables.
|
||||
7. **Critères d’acceptation** — concise checkboxes with measurable outcomes and evidence required.
|
||||
8. **Hors périmètre / dépendances** — identify related capabilities that must not be mistaken as delivered, required owners/access/hardware, and blockers.
|
||||
9. **Maquette** — attach/link only where UI design materially affects acceptance; otherwise say `Aucune maquette requise : ...` with a short reason.
|
||||
10. **Liens** — PRs, runs, skills, related issues and design artifacts.
|
||||
|
||||
Render long historical logs as a clearly separated `<details><summary>Historique détaillé</summary>` appendix. Lead with the latest state and the exact open work; do not make readers infer the task from a 1,000-word pasted paragraph. Use short paragraphs, bullets, and headings; expand acronyms on first use when the audience may not know them.
|
||||
|
||||
## Pull requests and closure
|
||||
|
||||
- Before opening/updating a PR, verify the issue number, link, acceptance criteria, focused skill, and test/acceptance evidence are present.
|
||||
- Keep `.gitea/PULL_REQUEST_TEMPLATE.md` aligned with this workflow: request the linked Gitea issue and observed CI/acceptance evidence; never direct contributors to update a markdown backlog.
|
||||
- Use `Closes #N` only when the PR completes every criterion owned by that issue. For partial work use `Refs #N` and leave the issue open with unchecked criteria and evidence updated.
|
||||
- Gitea closes a `Closes #N` issue when the PR merges. After merge, verify the issue state changed; if not, close it manually only after checking all criteria and posting the merge/CI/acceptance evidence.
|
||||
- Do not close tickets merely because code was merged when required acceptance (including the disposable Compose recipe, CI gate, external deployment, camera, storage, or release run) remains outstanding. Create a separate validation issue if code delivery and external validation have different owners or timelines.
|
||||
- On completion, leave a concise final issue comment linking merged PR/commit, successful checks and acceptance record, plus explicit limits. Keep the ticket searchable; don't erase the completion trace.
|
||||
|
||||
## Backlog maintenance
|
||||
|
||||
- Review open issues before planning work; deduplicate, label, prioritize, split oversized work, and refresh stale acceptance criteria.
|
||||
- For discovered follow-up work during a PR, create/link a ticket before treating it as deferred. Avoid checklist fragments in commits, skills, or docs that become a second backlog.
|
||||
- Repository skills contain durable workflows, not per-task status. Update the relevant skill in the same PR when implementation or acceptance procedure changes.
|
||||
- When migrating a legacy backlog, carry each actionable incomplete item to an open issue; carry completed entries to closed issue history or a closed migration/traceability issue with original PR/run references. Verify issue counts, titles, states, and links before deleting the file.
|
||||
The [.gitea pull request template](../../.gitea/PULL_REQUEST_TEMPLATE.md) must request issue linkage, observed evidence and limits, and the Heimdall release assessment. Use `Closes #N` only when every issue criterion is complete; otherwise use `Refs #N`.
|
||||
@@ -10,6 +10,8 @@ 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. 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.
|
||||
- Keep the GPU summary in `docs/README.md` aligned with `docs/gpu-runtime.md`: the default Agent remains CPU-only, an optional signed NVIDIA/CUDA amd64 image is published, and physical CUDA execution remains unvalidated until exercised on compatible hardware. Do not collapse these states into “published inference is CPU-only” or imply hardware validation from package/image publication.
|
||||
- Keep technical-spec summaries consistent with `AgentOptions`, `AnalysisMode`, ONNX provider selection, and `docs/gpu-runtime.md`: distinguish CPU-default inference and optional NVIDIA/CUDA inference from GPU inventory and FFmpeg media handling. AMD/Intel device visibility or detected NVENC/QSV/VAAPI capability is not evidence that ONNX inference or a media pipeline uses those accelerators. Treat remote broker mode as configurable behavior, not a validated inter-site deployment; do not publish throughput estimates without reproducible measurements and hardware/method details.
|
||||
- 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:
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ description: Diagnose and recover Heimdall startup from transient Hangfire Postg
|
||||
|
||||
Heimdall registers all recurring jobs synchronously after database migrations in `src/Heimdall.Web/Program.cs`. Hangfire's PostgreSQL storage acquires a distributed lock per recurring-job id during `AddOrUpdate`; `agent-failover` is currently the first registration after removing the legacy `heartbeat-monitor` id.
|
||||
|
||||
The Central dashboard route is mapped from the same Program.cs with `MapHangfireDashboard("/hangfire", ...)`, guarded by `HangfireAdminAuthorizationFilter` for `Admin.Jobs` or the Admin role, and omitted in `Testing`. When updating `docs/hangfire-usage.md`, verify the route and filter against these sources; do not copy a stale `UseHangfireDashboard` or `/admin/jobs` example.
|
||||
|
||||
## Implementation and diagnosis
|
||||
|
||||
- Inspect the GlitchTip event stack, app start time, event timestamps, and `Program.cs`/`JobSetup.cs` line references. A timeout names the contended job key; it proves lock contention, not the number or identity of competing processes.
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
---
|
||||
name: heimdall-dotnet
|
||||
description: Implement or review Heimdall .NET 10 application, EF Core persistence, and agent changes while preserving its clean architecture and audit backlog.
|
||||
description: Apply Heimdall's actual .NET project boundaries, provider profile, and local acceptance expectations.
|
||||
---
|
||||
|
||||
# Heimdall .NET work
|
||||
# Heimdall .NET profile
|
||||
|
||||
Read `AGENTS.md`, the relevant Gitea issue, and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md) first. Trace a feature through `Domain` → `Application` → `Infrastructure` → `Web` or `Agent` before editing; update only the layers that own the behavior.
|
||||
Use the shared [dotnet-engineering skill](/home/nonobis/skills/skills/dotnet-engineering/SKILL.md) for general C#, architecture, EF Core, validation, and testing practices, and the shared [Gitea delivery workflow](/home/nonobis/skills/skills/gitea-delivery-workflow/SKILL.md) for issue-to-delivery lifecycle. This file records Heimdall's concrete topology and compatibility constraints only.
|
||||
|
||||
For multi-layer work, use [parallel development with Orca](../parallel-development/SKILL.md) to dispatch non-overlapping layer tasks early, sequence shared contract decisions, and integrate the result before running combined verification.
|
||||
## Actual project boundaries
|
||||
|
||||
For persistence changes, inspect the entity configuration and latest migration, then verify PostgreSQL translation and transactions with focused integration tests. Keep migrations compatible with existing rows, record the data backfill or rollback requirement, and avoid client-side filtering on access-controlled queries.
|
||||
- `Heimdall.Domain` and `Heimdall.Domain.Primitives` contain domain policy and primitives. Domain does not depend on infrastructure or ASP.NET Core Identity.
|
||||
- `Heimdall.Application` owns use cases, application contracts, and ports such as `IIdentityAccountService` and `IApplicationDbContext`.
|
||||
- `Heimdall.Infrastructure` implements persistence, ASP.NET Core Identity adapters, and external-service adapters.
|
||||
- `Heimdall.Web` composes the HTTP/UI host; `Heimdall.Agent` owns camera/runtime behavior and its local persistence.
|
||||
- `Heimdall.Contracts` contains shared transport contracts; `Heimdall.Mdns` is a separate discovery component. Do not collapse these projects into a generic five-project diagram.
|
||||
|
||||
For detailed database access rules and the allowlist for unavoidable provider-specific SQL, follow [the EF Core persistence skill](../ef-core-persistence/SKILL.md).
|
||||
Before changing a cross-layer behavior, trace the actual caller and implementation through the projects above. Keep ASP.NET Identity types in Infrastructure and user references in domain records keyed by `Guid UserId`, with EF relationships configured by Infrastructure.
|
||||
|
||||
For application commands, validate at the boundary, enforce site/camera scope in the use case, and make external side effects retry-safe. For agent work, account for disconnected operation, bounded queues, cancellation, and resource disposal.
|
||||
## Persistence and compatibility
|
||||
|
||||
After the change, run the smallest meaningful test suite plus the build when public contracts change. Update the issue with what passed and what still requires a deployed runner, camera, network, or object store. Link it from the PR and close it only when all acceptance criteria are verified.
|
||||
- Central production persistence is PostgreSQL through EF Core in Infrastructure. Agent-local durable state and the camera-discovery database use SQLite. Preserve both provider behaviors when changing shared models or persistence contracts.
|
||||
- Add reviewed EF Core migrations for Central schema changes; never rewrite an applied migration. Preserve deployed data and validate upgrade behavior against the supported PostgreSQL schema. Identity model moves that retain the schema require the project's explicit empty migration and updated model snapshot.
|
||||
- Agent SQLite schemas have their own compatibility and migration path. Preserve existing local outbox data and validate upgrade behavior from supported on-disk versions.
|
||||
- Keep migration/checksum and release asset integrity procedures in their focused skills: [database migration startup](../database-migration-startup/SKILL.md), [installer checksum acceptance](../installer-checksum-acceptance/SKILL.md), and [release automation](../release-automation/SKILL.md).
|
||||
- Authorization for site/camera resources is enforced at API and application boundaries. Validate scope against the actual resource-access services; UI visibility is not authorization.
|
||||
|
||||
## Product documentation
|
||||
|
||||
When updating `docs/specs.md`, check entity/property names against `src/Heimdall.Domain/Entities` and `src/Heimdall.Domain/Enums`. A site registration token is stored only as `RegistrationTokenHash` plus expiry. Distinguish the `CameraEvent` type from conceptual event wording, and `Person` from its related `KnownFace` embeddings.
|
||||
|
||||
For identity behavior and its product acceptance paths, follow [Heimdall identity](../heimdall-identity/SKILL.md). For any behavior/deployment change, use the exact [disposable Compose recipe](../compose-disposable-recipe/SKILL.md) and any additional focused acceptance skill. Record local, CI, Compose, and real deployment/hardware evidence separately in the Gitea issue.
|
||||
@@ -5,9 +5,14 @@ description: Implement and review Heimdall account, password, session, email con
|
||||
|
||||
# Heimdall Identity workflow
|
||||
|
||||
Read `AGENTS.md`, the focused Gitea issue and [the Gitea ticket workflow](../gitea-ticket-workflow/SKILL.md), and the Identity wiring in `Infrastructure/DependencyInjection.cs` and `Web/Program.cs` before changing authentication.
|
||||
Apply the shared [secure identity lifecycle skill](/home/nonobis/skills/skills/secure-identity-lifecycle/SKILL.md), [dotnet engineering skill](/home/nonobis/skills/skills/dotnet-engineering/SKILL.md), and [Gitea delivery workflow](/home/nonobis/skills/skills/gitea-delivery-workflow/SKILL.md) for common identity security, .NET, and delivery rules. This skill records Heimdall's actual Identity model, composition, and product acceptance. Inspect the Identity wiring in `src/Heimdall.Infrastructure/DependencyInjection.cs` and `src/Heimdall.Web/Program.cs` before changing authentication.
|
||||
|
||||
When maintaining `docs/auth-roles.md` or identity summaries in `docs/specs.md`, verify their role names and default permission summaries against `Infrastructure/Security/AppPermissions.cs` and `Domain/Enums/UserRole.cs`. Heimdall has `Admin`, `Supervisor`, and `Viewer`; site/camera access is separately enforced through resource-access services, not represented by a generic `User` role. Keep the authentication summary in `docs/README.md` aligned with that guide and model.
|
||||
|
||||
Verify identity model examples against `Infrastructure/Identity/IdentityAppUser.cs`, `Domain/Entities/UserSite.cs`, and `Infrastructure/Data/Configurations/UserSiteConfiguration.cs`. Keep ASP.NET Identity in Infrastructure; `UserSite` stores the user ID without an Identity navigation, and Infrastructure maps that foreign key.
|
||||
|
||||
Before documenting UI/API authorization examples in `docs/auth-roles.md`, verify referenced pages, methods, policies, and routes against `Components/Routes.razor`, the page components, controllers, and `ResourceAccess`. Do not preserve generic authorization snippets that reference services or callbacks absent from the application; distinguish page authentication from API resource filtering.
|
||||
|
||||
- Identity owns password hashing, normalized account lookup, role membership, lockout, authenticator tokens, and email/password tokens. Do not duplicate password or token cryptography in Heimdall.
|
||||
- Keep ASP.NET Core Identity packages and types inside Infrastructure. Domain must not reference Identity; Application uses `IIdentityAccountService` and `IdentityAccount` only. Put Identity EF entities (`IdentityAppUser`, `IdentityAppRole`) and `UserManager`/`RoleManager` adapters in Infrastructure. Keep user-related Domain relationships keyed by `Guid UserId`; configure their foreign keys to the Infrastructure user entity.
|
||||
- When creating an Identity user, copy the generated `SecurityStamp` back into the application account before building the first session/JWT. Cover bootstrap and regular user creation with a relational session validation test.
|
||||
- Moving Identity model classes without changing tables should produce an explicit empty EF migration and a snapshot containing the Infrastructure entity types. Verify migration compatibility against PostgreSQL before release.
|
||||
|
||||
@@ -1,30 +1,10 @@
|
||||
---
|
||||
name: infisical-secrets
|
||||
description: Retrieve and maintain Heimdall project credentials in the connected Infisical instance while keeping secret values out of repository files, transcripts, and logs.
|
||||
description: Route Heimdall secret access through shared Infisical guidance without retaining a credential inventory in the repository.
|
||||
---
|
||||
|
||||
# Heimdall secrets in Infisical
|
||||
# Heimdall Infisical profile
|
||||
|
||||
Use this workflow whenever a Heimdall skill needs a real credential, and link this skill from any skill that adds or changes a credential workflow. The connected MCP server is the supported interface to Infisical.
|
||||
Follow the shared [Infisical CLI skill](/home/nonobis/skills/skills/infisical-cli/SKILL.md) for selecting project/environment/path, retrieving only named secrets, safe process handoff, and metadata-only verification. This file contains no credential values or inventory of secret names.
|
||||
|
||||
## Vault and scope
|
||||
|
||||
- Select project **Orca** (`orca-cc2-m`) explicitly; its project ID is `96fb3628-2ee3-45b5-b6a8-66a0212a5b46`. Use `dev`, `staging`, or `prod` only when the task names that environment. Never silently fall back from one environment to another.
|
||||
- Use the MCP tools `list-projects`, `list-secrets`, `get-secret`, and `create-secret`. They are allowlisted in the local MCP configuration. Never use `create-secret` as an implicit overwrite operation: check the key first and explain/ask before replacing an existing value.
|
||||
- `list-secrets` returns secret values as well as names. Treat its full response as sensitive even when only checking availability. Do not print, quote, summarize, or copy values into tool output, chat, shell history, command arguments, files in the repository, issue/PR text, or logs.
|
||||
- Prefer retrieving only the needed key with `get-secret`. Pass the value directly to the one process that needs it using a protected stdin/temporary file outside the repository with mode `0600`, then remove that exact file. Never interpolate it into a command string or a checked-in Compose file.
|
||||
- Use metadata-only checks to report which keys exist. Never test access by dumping a value. If a diagnostic accidentally emits a value, stop, do not repeat it, and tell the user that the credential should be rotated. Do not rotate it unless the user explicitly asks.
|
||||
|
||||
## Using secrets in skill workflows
|
||||
|
||||
- Distinguish real deployment credentials from disposable acceptance credentials. Compose acceptance recipes must generate unique synthetic credentials and must not fetch production or staging values from Infisical.
|
||||
- For local manual integration work, fetch only the named development key needed by that skill. For a deployment task, use the explicitly requested environment and target. Never place fetched values in `.env.example`, tracked configuration, source, fixtures, or documentation.
|
||||
- CI secrets remain in the CI secret store unless a task explicitly migrates the CI workflow. Infisical presence alone does not configure Gitea Actions or prove a runner can access the vault.
|
||||
- When a workflow needs a credential not present in the selected environment, report its exact key name and purpose; do not substitute a similarly named credential or a different environment.
|
||||
- When asked to persist a newly provided credential, use `create-secret` in the selected project/environment/path. First verify the key is absent, then create it, then verify presence by listing metadata only. Do not echo the supplied value.
|
||||
|
||||
## Current inventory verified 2026-11-10
|
||||
|
||||
The `dev` root currently contains `GITEA_ORCA_TOKEN`, `HEIMDALL_LOGIN`, `HEIMDALL_PASSWORD`, `HEIMDALL_PRIVATE_KEY_B64`, `HEIMDALL_URL`, `PENPOT_LOGIN`, `PENPOT_PASSWORD`, and `PENPOT_URL`. The `staging` and `prod` roots were empty at verification time. Treat this inventory as a dated snapshot; check metadata again before relying on it.
|
||||
|
||||
The development inventory does not include Heimdall deployment/database/JWT, RustFS, Agent site-token, Coturn, Redis, Sentry, Docker Hub, or release-signing credentials. Some are generated for disposable acceptance, some are optional, and CI publication credentials belong in Gitea Actions. Do not add real values simply to make the inventory look complete; report only keys required by the active task.
|
||||
Heimdall's disposable Compose acceptance uses generated synthetic credentials; do not retrieve deployment credentials for those recipes. CI publication credentials remain in the configured Gitea Actions secret store. Infisical configuration or vault changes are outside the scope of this repository skill.
|
||||
@@ -1,17 +1,10 @@
|
||||
---
|
||||
name: mcp-global-configuration
|
||||
description: Keep Heimdall developer MCP integrations available across projects without storing machine credentials in the repository.
|
||||
description: Keep Heimdall developer MCP integrations in the user-level agent configuration.
|
||||
---
|
||||
|
||||
# Heimdall developer MCP configuration
|
||||
# Heimdall MCP profile
|
||||
|
||||
MCP integrations used while maintaining Heimdall belong in the developer's global Codex configuration, not in a repository `.mcp.json`. This keeps each project checkout free of personal service tokens and makes the integrations available in other projects.
|
||||
Follow the shared [MCP configuration skill](/home/nonobis/skills/skills/mcp-configuration/SKILL.md) for provider formats, configuration scope, validation, and credential handling.
|
||||
|
||||
## Configuration workflow
|
||||
|
||||
1. Before changing MCP setup, read this skill and the linked Gitea issue.
|
||||
2. Configure the intended servers in `~/.codex/config.toml`. Keep authentication values in user-level configuration or environment variables; never copy them into tracked files, examples, logs, or acceptance output.
|
||||
3. Remove any repository `.mcp.json` that duplicates global server configuration and contains credentials.
|
||||
4. Validate that the global TOML parses and run `codex mcp list`. Check that each expected server appears once and is enabled.
|
||||
5. For a server needed by the task, make a harmless read-only request (for example, list accessible GlitchTip organizations) to confirm authentication. Do not claim remote access from config presence alone.
|
||||
6. Update the corresponding Gitea issue with the local verification and any limits. Do not add an application Compose acceptance recipe for a developer-only MCP configuration change.
|
||||
Heimdall developer MCP integrations belong in the user's global Codex configuration, not in a repository `.mcp.json`. This repository skill documents that scope only; it does not store server credentials or authorize changes to local/global MCP configuration during a repository documentation task.
|
||||
@@ -7,6 +7,10 @@ description: Implement and accept the authenticated Heimdall in-app notification
|
||||
|
||||
The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser.
|
||||
|
||||
When documenting delivery channels in `docs/notifications.md` or its summary in `docs/specs.md`, verify `NotificationChannel`, `SendNotificationJob`, `NotificationSettingsSection.razor`, `Profile.razor`, the delivery services, and `BackgroundJobs/JobSetup.cs`. The shipped external channels are SMTP email and ntfy; do not describe Gotify as integrated. `/settings` owns global SMTP/ntfy settings and test actions, while `/profile` owns user preferences. Check both digest job implementations and their schedules before documenting cadence. Distinguish source inspection from validation against a real SMTP/ntfy deployment. Remove obsolete channel integrations, editor flows, and test claims from `docs/notifications.md` and `docs/specs.md`; if a historical example must remain, label that exact heading/table/snippet locally rather than relying on a broad notice elsewhere in the guide. When the notification guide’s scope or delivered status changes, update both notification summaries in `docs/README.md` to match it.
|
||||
|
||||
When legacy notification designs remain in `docs/MASTER_SPECIFICATION.md`, put a local dated historical/non-shipped note beside each section, queue example, or UI mockup, and link to `docs/notifications.md`. A document-level historical header alone is not sufficient for Gotify or template-editor claims.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests.
|
||||
|
||||
@@ -16,6 +16,7 @@ The Linux and Windows server installers save service secrets in `<install-root>/
|
||||
|
||||
## coturn
|
||||
|
||||
- Coturn is an optional live-view relay consumed by Central through `LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns short-lived TURN REST credentials to the browser; the shared secret stays server-side. Keep this service optional and do not describe its integration as future or external-only.
|
||||
- Keep `coturn_secret` sourced from `./optional/secrets/coturn_secret`.
|
||||
- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a short root initializer and write its configuration into private tmpfs. Do not print the value or pass it in the server process arguments.
|
||||
- Local Compose secrets are owner-only bind mounts too. Start the initializer as root, make the temporary config readable by the image's `nobody` account, then `exec` `turnserver` as `nobody` with `no-new-privileges` enabled. Keep the root init transient; do not run the TURN daemon as root.
|
||||
|
||||
@@ -1,45 +1,14 @@
|
||||
---
|
||||
name: parallel-development
|
||||
description: Plan and coordinate parallel Heimdall implementation work with Orca workers while preserving architecture, issue tracking, and acceptance evidence.
|
||||
description: Apply Orca's shared coordination workflow with Heimdall's project boundaries and acceptance gates.
|
||||
---
|
||||
|
||||
# Parallel development with Orca
|
||||
# Heimdall parallel work profile
|
||||
|
||||
Use this workflow for a Heimdall change that can be split into independent investigations or implementation tasks. Read `AGENTS.md`, the focused Gitea issue, the relevant domain skills, and the installed Orca `orchestration` guide first. The Orca CLI guide is also required when creating or managing worktrees. The version-matched instructions come from `orca-ide skills get orchestration` and `orca-ide skills get orca-cli`; follow the resolved executable specified by those guides.
|
||||
Use the shared [Orca parallel work skill](/home/nonobis/skills/skills/orca-parallel-work/SKILL.md) for Runs, Tasks, dependencies, worker assignment, and integration ownership. Use the shared [Gitea delivery workflow](/home/nonobis/skills/skills/gitea-delivery-workflow/SKILL.md) for durable issue tracking. This file supplies only Heimdall-specific boundaries.
|
||||
|
||||
## Find parallel work early
|
||||
Map work to the real projects: `Heimdall.Domain` and `Heimdall.Domain.Primitives`; `Heimdall.Application`; `Heimdall.Infrastructure`; `Heimdall.Web`; `Heimdall.Agent`; and, when applicable, `Heimdall.Contracts` or `Heimdall.Mdns`. Keep Domain independent, use cases/ports in Application, adapters and EF Core in Infrastructure, HTTP/UI composition in Web, and camera/runtime behavior in Agent.
|
||||
|
||||
1. Map the requested outcome to the Heimdall boundaries: `Domain`, `Application`, `Infrastructure`, `Web`, and `Agent`. Also identify tests, migrations, documentation, and disposable acceptance work.
|
||||
2. List concrete work packages with a single owner, bounded files or components, required inputs, and an observable deliverable. Mark each dependency explicitly.
|
||||
3. Start every ready, independent investigation or implementation promptly. Keep sequential work (shared contract decisions, migration ordering, integration, final acceptance, ticket update, and PR) with the coordinator unless it is itself safely isolated.
|
||||
4. Split independent, user-visible deliverables into linked Gitea issues before dispatch, following `gitea-ticket-workflow`. Keep one issue for coordinated subtasks that do not ship independently.
|
||||
When persistence work is split, keep Central PostgreSQL model/migration ownership separate from Agent SQLite schema work. See [Heimdall persistence](../ef-core-persistence/SKILL.md) for provider boundaries.
|
||||
|
||||
Choose the Orca coordination shape that matches the dependency graph:
|
||||
|
||||
- For a small set of independent tasks with clear, separate outputs, use the version-matched `worker-start --spec` workflow. Give workers precise scope and tell them to report evidence and blockers.
|
||||
- For dependent tasks or several waves of work, create an Orca Run and Tasks with explicit dependencies, then start all Tasks reported ready. Recheck readiness after each worker report and start newly unblocked work without waiting for unrelated branches.
|
||||
- Use a shared current worktree only when workers cannot conflict in files. If edits overlap or cannot be partitioned confidently, assign separate Orca worktrees and integrate their changes deliberately. Do not start concurrent workers that edit the same files.
|
||||
- Do not parallelize a decision that needs one owner, duplicate the same task across workers, or turn a straightforward isolated change into coordination overhead.
|
||||
|
||||
## Heimdall task contracts
|
||||
|
||||
Every worker brief must include the user outcome, issue number, exact component/file ownership, architectural constraints, dependencies, acceptance evidence, and what to return. Ask for a concise report with files changed, commands/evidence, remaining risks, and any files or decisions needed from the coordinator. Do not provide credentials, production data, RTSP URLs, raw tokens, or real customer information in a worker prompt.
|
||||
|
||||
Workers must preserve these boundaries:
|
||||
|
||||
- Domain stays independent of infrastructure; use cases and interfaces belong in Application; adapters and EF Core persistence belong in Infrastructure; HTTP/UI composition belongs in Web; camera/runtime behavior belongs in Agent.
|
||||
- EF Core and PostgreSQL requirements remain in force. Do not share a `DbContext` across concurrent work. Schema changes include reviewed migrations and relational verification.
|
||||
- Each worker edits only its assigned scope. When shared contracts must change, have one owner define the contract first, then unblock dependent tasks in the Orca DAG.
|
||||
- Each independent implementation still follows its focused skill and records results against the Gitea issue. Delegation does not waive authorization, security, CI runner, secret, or review rules.
|
||||
|
||||
## Integrate and validate once
|
||||
|
||||
1. Coordinate through Orca messages and worker reports, not by polling or steering worker terminals. Follow the version-matched guide's wake, recovery, and completion rules; do not treat silence as proof of completion.
|
||||
2. Review each returned diff against its assigned scope and the issue criteria. Resolve overlapping changes in the coordinator's integration step; do not accept a report as proof without inspecting the relevant change/evidence.
|
||||
3. Run shared builds, tests, persistence checks, and disposable Compose acceptance after integrating dependent changes. Avoid making every worker rerun the same full suite; ask each worker for focused evidence, then run the smallest combined checks once at integration.
|
||||
4. Keep required project-specific acceptance intact. Behavior and deployment changes still use `compose-disposable-recipe`; account bootstrap and Central update changes use their additional focused recipes. Never claim external runner, registry, camera, or storage evidence from a worker's local mock.
|
||||
5. Update the issue with completed criteria and actual evidence, create/update the PR with `Closes #N` only when every criterion is complete (otherwise `Refs #N`), and record unresolved external validation separately.
|
||||
|
||||
## Completion record
|
||||
|
||||
The issue or PR should make the coordination auditable without duplicating a long-lived backlog: note the Orca work packages at a high level, which were integrated, the combined checks actually run, and any tasks or acceptance gates still open. Close or settle worker Tasks only when their evidence is received; a reported failure remains open work.
|
||||
Every behavior or deployment change still uses the exact [disposable Compose recipe](../compose-disposable-recipe/SKILL.md). Add [first-admin bootstrap](../first-admin-bootstrap/SKILL.md), [Central auto-update](../central-auto-updates/SKILL.md), or other focused acceptance workflows where the changed behavior requires them.
|
||||
@@ -1,32 +1,14 @@
|
||||
---
|
||||
name: pr-release-versioning
|
||||
description: Assess whether a Heimdall pull request needs a published release and select its SemVer increment from the change impact without asking the user.
|
||||
description: Apply Heimdall's version source and release impact policy when preparing a pull request.
|
||||
---
|
||||
|
||||
# Pull request release assessment
|
||||
# Heimdall release profile
|
||||
|
||||
Apply this assessment while preparing every Heimdall PR. Do not ask the user whether to release or which version to use. Record the decision, rationale, and proposed version in the PR description; update it if the diff changes.
|
||||
Use the shared [release assessment skill](/home/nonobis/skills/skills/release-assessment/SKILL.md) for the assessment expected in every PR. This profile defines Heimdall's SemVer source and impact mapping.
|
||||
|
||||
## Decide whether a release is needed
|
||||
|
||||
- **No release** for documentation, skills, tests, CI-only changes, refactors with no externally observable change, or internal tooling changes. State `Release: no` and keep the current version unchanged.
|
||||
- **Release required** when the PR changes behavior shipped to Heimdall users or operators, published images/installers/Agent assets, compatibility contracts, or security fixes that users need to receive.
|
||||
- Do not create a release tag for a PR. A release tag points to a commit on `main`; assess the merged change after required checks pass and then follow the tag workflow in `release-automation`.
|
||||
|
||||
## Select the version automatically
|
||||
|
||||
Use the latest stable SemVer tag reachable from the integration branch (`MAJOR.MINOR.PATCH`); ignore prerelease tags when selecting the stable base. For multiple merged, unreleased changes, assess all changes since that tag together and use the highest required increment.
|
||||
|
||||
- **MAJOR** for a breaking API, configuration, data, or install/upgrade compatibility change.
|
||||
- **MINOR** for a backward-compatible user-facing capability or operator feature.
|
||||
- **PATCH** for backward-compatible bug fixes, security fixes, performance fixes, and shipped compatibility corrections.
|
||||
- No release-worthy changes means no tag and no version increment.
|
||||
|
||||
Increment only the selected component and reset lower components to zero. For example, from `1.4.7`: breaking becomes `2.0.0`, a compatible feature becomes `1.5.0`, and a fix becomes `1.4.8`. If no stable tag exists, use `1.0.0` as the base only when the repository's first-release policy confirms that baseline; otherwise report the missing baseline instead of inventing one.
|
||||
|
||||
## PR and post-merge steps
|
||||
|
||||
- Put a short `Release assessment` section in every PR: `no release (reason)` or `release required; proposed version X.Y.Z (reason)`.
|
||||
- For no-release PRs, do not create or push a tag. Keep the version unchanged.
|
||||
- For a release-required PR, determine the exact next version from the current `main` tags after merge, verify it is unused, and create an annotated tag on the merged `main` commit only after required CI succeeds. If another merge changes the base before tagging, recalculate from the latest stable tag and all unreleased changes.
|
||||
- Never overwrite or move an existing tag. If the change is prerelease-only or an emergency exception, explain the project-specific suffix/tag choice in the PR without asking the user to choose it.
|
||||
- Documentation, skills, tests, CI-only changes, and internal refactors without externally observable impact have `Release: no`; do not change the version or create a tag for them.
|
||||
- A breaking user-facing API, configuration, data, or install/upgrade contract requires a major increment. A backward-compatible user/operator capability requires a minor increment. A backward-compatible shipped fix or security fix requires a patch increment.
|
||||
- Use the latest stable SemVer tag reachable from `main` as the base and account for all unreleased changes since that tag. Ignore prerelease tags when selecting the stable base. If no stable tag exists, use `1.0.0` only if the repository's first-release policy confirms it; otherwise report the missing baseline.
|
||||
- The PR body records either `Release: no — <reason>` or `Release: required — proposed <version> (<reason>)`. Recalculate if the PR diff or `main` changes.
|
||||
- Never tag before the merged commit is on `main` and required checks succeed. Follow [release automation](../release-automation/SKILL.md) for the signed Heimdall assets and image digest workflow. Never move or overwrite an existing release tag.
|
||||
@@ -5,7 +5,7 @@ description: Build and validate changed Heimdall images on pushes, then publish
|
||||
|
||||
# Heimdall build and release workflow
|
||||
|
||||
For every PR, follow [pull request release assessment](../pr-release-versioning/SKILL.md). Determine and record whether a release is needed and the proposed SemVer from the change impact; do not ask the user to decide. Documentation and skills-only changes do not create a release or change the version. Only tag a release after the merged commit is on `main` and required checks pass.
|
||||
Apply the shared [DevOps engineering skill](/home/nonobis/skills/skills/devops-engineering/SKILL.md) for CI, runner, publication-secret, and deployment security. For PR impact assessment, follow [shared release assessment](/home/nonobis/skills/skills/release-assessment/SKILL.md) together with the [Heimdall SemVer profile](../pr-release-versioning/SKILL.md). Documentation and skills-only changes do not create a release or change the version. Only tag a release after the merged commit is on `main` and required checks pass.
|
||||
|
||||
For any local release investigation that needs credentials, follow [Infisical secrets](../infisical-secrets/SKILL.md). Keep publication credentials in Gitea Actions as specified below; do not assume that a key in Infisical is available to CI.
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ 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.
|
||||
|
||||
- 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.
|
||||
- When documenting health status, compare each summary with the registered check names/tags, endpoint filters, and HTTP status mapping in Web and Agent. Web `/healthz` is liveness (`200`), `/readyz` checks the `ready` PostgreSQL and selected-storage dependencies (`200` only when healthy, otherwise `503`), and `/health/live` selects the `live` PostgreSQL and optional configured AI backend check (`503` when degraded). Agent `/healthz` runs its registered checks (`Degraded` maps to `200`, `Unhealthy` to `503`); `/health/live` selects only the Agent pipeline-degradation check (`503` when degraded). Do not claim a Central broker health check unless one is registered.
|
||||
- Ollama is optional; its URL can be configured in Central settings, the admin connectivity action can ping it, and `AiHealthCheck` probes `/api/tags`. That endpoint check proves availability only, not model inference or summary generation. Do not document LLM-generated summaries until a production caller for a model generation/chat API is implemented.
|
||||
- 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. 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.
|
||||
@@ -16,6 +18,8 @@ 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.
|
||||
|
||||
When updating implementation-status documentation, verify both `src/Heimdall.Web/Program.cs` and `src/Heimdall.Agent/Program.cs` for exporter registration and `/metrics` mapping, then compare the documented signal inventory with `docs/metrics.md` and example alert rules with `deploy/prometheus/heimdall-alerts.yml`. Mark exporter implementation separately from an operator's Prometheus scrape, deployed alerting, or threshold validation; local or CI evidence does not establish those external states.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
name: signalr-documentation
|
||||
description: Keep the Heimdall SignalR guide aligned with mapped routes, Hub RPC methods, broadcast events, authentication and resource authorization.
|
||||
---
|
||||
|
||||
# Heimdall SignalR documentation workflow
|
||||
|
||||
Use this skill when changing a hub, SignalR authentication, subscription handling, broadcast contract or `docs/signalr-usage.md`.
|
||||
|
||||
## Source of truth
|
||||
|
||||
- Routes are mapped in `src/Heimdall.Web/Program.cs` beside the `MapHub<T>` calls.
|
||||
- Client-invokable Hub methods belong inside the concrete `Hub` subclass. Nearby `*BroadcastService` methods are server-side application services and must not be documented as client RPC methods.
|
||||
- Server-to-client event names and payload arguments are the `SendAsync` calls in the corresponding broadcast service.
|
||||
- Authentication schemes and token extraction come from each Hub's `[Authorize]` attribute, `ConfigureJwtBearerAuthentication` in `Program.cs`, and `ApiKeyAuthenticationHandler.ResolveApiKeyFromRequest`.
|
||||
- Resource-level subscriptions and reauthorization are implemented by the Hub methods, `ResourceAccess`, and `LiveSubscriptions.AuthorizedAsync`.
|
||||
- Actual clients are `src/Heimdall.Agent/Services/ConfigReceiverService.cs` and `src/Heimdall.Web/Services/NotificationsHubClient.cs`.
|
||||
- Hub authorization/isolation tests are under `tests/Heimdall.Web.Tests/Hubs/`.
|
||||
|
||||
## Update procedure
|
||||
|
||||
1. Read the route map and inspect the full Hub subclass before listing its public methods.
|
||||
2. Record separately: auth scheme, caller join/leave methods, site/camera/Agent checks, group/channel key, broadcast messages, and payload shape.
|
||||
3. Follow every broadcast message to the actual `SendAsync` call; omit planned or legacy messages that are not sent by current code.
|
||||
4. Check whether recipients are filtered at subscribe time, reauthorized at send time, or both. Never describe a global group as unrestricted when a current access check exists.
|
||||
5. Inspect the real clients for token providers, initial API loads, retries/reconnect behavior and fallback. Do not expose token values or imply browser cookie auth where the Hub requires JWT.
|
||||
6. Confirm every documented route appears in `Program.cs`; explicitly label absent routes as planned/unmapped rather than available.
|
||||
7. Link the focused tests and distinguish unit/CI evidence from proxy, network or deployment validation.
|
||||
8. Review `docs/signalr-usage.md` for unsupported event names, copied pseudocode, stale security claims, and missing limits on delivery/replay.
|
||||
|
||||
When the SignalR or live-view summary in `docs/MASTER_SPECIFICATION.md` changes, treat that file's dated architecture sections as historical unless verified against the mapped routes and current media path. Keep the mapped hub list exact, do not describe a planned hub or peer-to-peer media path as shipped, and link readers to `docs/signalr-usage.md` and `docs/docker-compose.md` for current contracts and deployment guidance. If retaining superseded material, put a historical-status note immediately before each affected diagram, roadmap phase, UI mockup, or target-results block; a header-only disclaimer is insufficient for those detailed examples.
|
||||
|
||||
Do not add runtime behavior in a documentation-only change. If the audit reveals a behavior defect, create a separate Gitea issue before implementation and keep the documentation explicit about the current state.
|
||||
@@ -9,6 +9,8 @@ Heimdall renders its root `Routes` component in an interactive server circuit wi
|
||||
|
||||
The reusable interactive error screen is `Components/Pages/NotFound.razor`. It owns its `MainLayout`, title/body localization, and the return link to `/dashboard`. Keep it assigned as `Router.NotFoundPage` for client-side unknown navigation. Keep the static HTTP fallback's resource keys and link target aligned with this component.
|
||||
|
||||
When maintaining route documentation or the UI summary in `docs/specs.md`, verify current routes against the Razor `@page` directives and point detailed inventories to `docs/ui-pages.md` instead of copying a hard page count. Also check route examples in navigation and authorization guides against the current layout links and their visibility conditions. Mark removed mockups as historical and link to the replacement pages; do not preserve a retired route such as `/admin` as if it were still mapped.
|
||||
|
||||
## Acceptance workflow
|
||||
|
||||
1. In `tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs`, verify a direct unknown URL returns HTTP 404 and displays the localized title and return link in its static response.
|
||||
|
||||
@@ -9,7 +9,9 @@ and external network behavior is measured.
|
||||
|
||||
- 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.
|
||||
publisher when assignment, enablement, or Agent lifetime ends. A source URL
|
||||
change for the same camera must also stop the old publisher and start one from
|
||||
the new configuration before synchronization is considered complete.
|
||||
- Use MediaMTX as the WebRTC/WHEP media server. Agent publishes the camera's
|
||||
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
|
||||
@@ -30,6 +32,23 @@ and external network behavior is measured.
|
||||
FFmpeg process count, and session lifetime. Ensure cancellation/config changes
|
||||
reap child processes and release permits.
|
||||
|
||||
## Source-change lifecycle acceptance
|
||||
|
||||
`LiveCameraRelayService` compares the effective RTSP source configured for each
|
||||
camera (substream when configured, otherwise primary stream) with the source attached to its running FFmpeg relay. If the source
|
||||
changes while the CameraId remains assigned and enabled, synchronization stops
|
||||
and disposes the old process before starting a relay with the updated source.
|
||||
The normal synchronization interval is five seconds.
|
||||
|
||||
Run `bash skills/webrtc-live/source-change-acceptance.sh` for the focused
|
||||
disposable Compose acceptance. It packages tracked and non-ignored source into
|
||||
an isolated .NET 10 SDK container and runs the Agent relay tests, including the
|
||||
same-CameraId primary and substream source changes, unchanged-source stability, renewal-boundary,
|
||||
child-process stop, and log-redaction assertions. It publishes no host ports,
|
||||
uses no persistent volumes or deployment credentials, builds no local image,
|
||||
and keeps only the upstream SDK image. The EXIT trap tears down the unique
|
||||
Compose project and verifies its containers, volumes, and network are absent.
|
||||
|
||||
## Implementation references
|
||||
|
||||
Use MediaMTX's maintained documentation as the protocol reference:
|
||||
@@ -44,6 +63,29 @@ Use MediaMTX's maintained documentation as the protocol reference:
|
||||
Use H.264 without B-frames for browser compatibility and latency. Validate
|
||||
actual negotiation in browsers; a successful RTSP publish does not prove WHEP.
|
||||
|
||||
## User-facing documentation source of truth
|
||||
|
||||
When updating `docs/specs.md` or `docs/ui-pages.md`, trace each shipped claim to
|
||||
the current implementation:
|
||||
|
||||
- The camera detail route and embedded Watch/Stop controls are in
|
||||
`src/Heimdall.Web/Components/Pages/CameraDetail.razor`; the browser module is
|
||||
`src/Heimdall.Web/wwwroot/js/live-view.js`. Do not document a separate
|
||||
`/cameras/{id}/live` route or rename the module to `liveView.js`.
|
||||
- When documenting role visibility in `docs/auth-roles.md`, use the camera detail route for the embedded live-view and trace session permission to `LiveMediaController`; the endpoint requires `Camera.Read` plus camera-level access, not a separate `Camera.Live` endpoint policy.
|
||||
- Session creation/release, authorization, short-lived tickets, WHEP URL and
|
||||
ICE configuration are in `src/Heimdall.Web/Controllers/LiveMediaController.cs`.
|
||||
- Agent RTSP publication and FFmpeg lifecycle are in
|
||||
`src/Heimdall.Agent/Services/LiveCameraRelayService.cs`.
|
||||
- Describe the current media path as Agent RTSP(S) publication to MediaMTX and
|
||||
browser WHEP/WebRTC playback. SignalR hubs carry no video media or live-view
|
||||
SDP/ICE signaling.
|
||||
- Separate implementation and synthetic acceptance evidence from real camera,
|
||||
external ICE/TURN and latency measurements. Track those external results in
|
||||
#161; keep the 503/configuration investigation in #341.
|
||||
- Before preserving a proposed control or performance target in a UI mockup,
|
||||
mark it as planned and verify it is not presented as shipped behavior.
|
||||
|
||||
## Required acceptance
|
||||
|
||||
Run from changed source in an isolated disposable Compose project with unique
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')"
|
||||
project="heimdall-live-source-change-${suffix}"
|
||||
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")"
|
||||
compose_file="${temp_dir}/compose.json"
|
||||
source_archive="${temp_dir}/source.tar"
|
||||
local_image_tags=()
|
||||
|
||||
if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
|
||||
printf 'Docker Compose is required for live source-change acceptance.\n' >&2
|
||||
rmdir -- "$temp_dir"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
cleanup_failed=0
|
||||
if [[ -f "$compose_file" ]]; then
|
||||
docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
|
||||
fi
|
||||
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 -f -- "$compose_file" "$source_archive" || cleanup_failed=1
|
||||
rmdir -- "$temp_dir" || cleanup_failed=1
|
||||
if (( cleanup_failed )); then
|
||||
printf 'Disposable acceptance cleanup failed for project %s\n' "$project" >&2
|
||||
status=1
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
python3 - "$compose_file" "$source_archive" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
compose_path, archive_path = sys.argv[1:]
|
||||
test_command = """set -euo pipefail
|
||||
mkdir -p /tmp/heimdall-source
|
||||
tar -xf /source.tar -C /tmp/heimdall-source
|
||||
cd /tmp/heimdall-source
|
||||
dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode
|
||||
dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore --configuration Release -m:1 --filter FullyQualifiedName~LiveCameraRelayServiceTests
|
||||
"""
|
||||
document = {
|
||||
"services": {
|
||||
"source-change-tests": {
|
||||
"image": "mcr.microsoft.com/dotnet/sdk:10.0",
|
||||
"entrypoint": ["bash", "-euc"],
|
||||
"command": [test_command],
|
||||
"volumes": [f"{archive_path}:/source.tar:ro"],
|
||||
}
|
||||
}
|
||||
}
|
||||
with open(compose_path, "w", encoding="utf-8") as compose_file:
|
||||
json.dump(document, compose_file)
|
||||
PY
|
||||
|
||||
# Archive only tracked and non-ignored working files; exclude multi-gigabyte
|
||||
# ignored build/model outputs from the disposable SDK container.
|
||||
git -C "$repo_root" ls-files -z --cached --others --exclude-standard |
|
||||
tar -C "$repo_root" --null -T - -cf "$source_archive"
|
||||
|
||||
printf 'Project: %s\n' "$project"
|
||||
printf 'Local images built: none (upstream .NET SDK image only)\n'
|
||||
docker compose -p "$project" -f "$compose_file" up --abort-on-container-exit --exit-code-from source-change-tests
|
||||
@@ -5,20 +5,85 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>Re-publishes assigned primary streams to the configured Central MediaMTX.</summary>
|
||||
public sealed class LiveCameraRelayService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
CameraConfigStore cameras,
|
||||
IHttpClientFactory clients,
|
||||
ILogger<LiveCameraRelayService> logger) : BackgroundService
|
||||
internal interface ILiveRelayProcess : IDisposable
|
||||
{
|
||||
bool HasExited { get; }
|
||||
void KillEntireProcessTree();
|
||||
Task WaitForExitAsync(TimeSpan timeout);
|
||||
}
|
||||
|
||||
internal interface ILiveRelayProcessFactory
|
||||
{
|
||||
ILiveRelayProcess? Start(ProcessStartInfo startInfo);
|
||||
}
|
||||
|
||||
internal sealed class LiveRelayProcessFactory : ILiveRelayProcessFactory
|
||||
{
|
||||
public ILiveRelayProcess? Start(ProcessStartInfo startInfo)
|
||||
{
|
||||
var process = Process.Start(startInfo);
|
||||
if (process is null) return null;
|
||||
_ = DrainErrorsAsync(process);
|
||||
return new LiveRelayProcess(process);
|
||||
}
|
||||
|
||||
private static async Task DrainErrorsAsync(Process process)
|
||||
{
|
||||
try { while (await process.StandardError.ReadLineAsync() is not null) { } }
|
||||
catch (IOException) { }
|
||||
}
|
||||
|
||||
private sealed class LiveRelayProcess(Process process) : ILiveRelayProcess
|
||||
{
|
||||
public bool HasExited => process.HasExited;
|
||||
public void KillEntireProcessTree() => process.Kill(entireProcessTree: true);
|
||||
public Task WaitForExitAsync(TimeSpan timeout) => process.WaitForExitAsync().WaitAsync(timeout);
|
||||
public void Dispose() => process.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-publishes assigned effective camera streams to the configured Central MediaMTX.</summary>
|
||||
public sealed class LiveCameraRelayService : BackgroundService
|
||||
{
|
||||
private readonly AgentState _state;
|
||||
private readonly IOptions<AgentOptions> _options;
|
||||
private readonly CameraConfigStore _cameras;
|
||||
private readonly IHttpClientFactory _clients;
|
||||
private readonly ILiveRelayProcessFactory _processFactory;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly ILogger<LiveCameraRelayService> _logger;
|
||||
private const int MaxPublishers = 2;
|
||||
private readonly Dictionary<Guid, Relay> _relays = [];
|
||||
private readonly Dictionary<Guid, DateTimeOffset> _retryAt = [];
|
||||
private sealed record Relay(Process Process, DateTimeOffset RenewAt);
|
||||
private sealed record Relay(ILiveRelayProcess Process, DateTimeOffset RenewAt, string SourceUrl);
|
||||
private sealed record PublishSession(string Url, DateTimeOffset RenewAt);
|
||||
|
||||
public LiveCameraRelayService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
CameraConfigStore cameras,
|
||||
IHttpClientFactory clients,
|
||||
ILogger<LiveCameraRelayService> logger)
|
||||
: this(state, options, cameras, clients, new LiveRelayProcessFactory(), TimeProvider.System, logger) { }
|
||||
|
||||
internal LiveCameraRelayService(
|
||||
AgentState state,
|
||||
IOptions<AgentOptions> options,
|
||||
CameraConfigStore cameras,
|
||||
IHttpClientFactory clients,
|
||||
ILiveRelayProcessFactory processFactory,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<LiveCameraRelayService> logger)
|
||||
{
|
||||
_state = state;
|
||||
_options = options;
|
||||
_cameras = cameras;
|
||||
_clients = clients;
|
||||
_processFactory = processFactory;
|
||||
_timeProvider = timeProvider;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
@@ -27,7 +92,7 @@ public sealed class LiveCameraRelayService(
|
||||
{
|
||||
try { await SynchronizeAsync(stoppingToken); }
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
catch (Exception ex) { logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); }
|
||||
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; }
|
||||
}
|
||||
@@ -35,26 +100,27 @@ public sealed class LiveCameraRelayService(
|
||||
finally { await StopAllAsync(); }
|
||||
}
|
||||
|
||||
private async Task SynchronizeAsync(CancellationToken ct)
|
||||
internal async Task SynchronizeAsync(CancellationToken ct)
|
||||
{
|
||||
var assigned = SelectAssignedCameras(cameras);
|
||||
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;
|
||||
relay.RenewAt > _timeProvider.GetUtcNow() &&
|
||||
string.Equals(relay.SourceUrl, camera.EffectiveRtspUrl, StringComparison.Ordinal)) 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);
|
||||
if (_state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(_state.ApiKey) ||
|
||||
_retryAt.GetValueOrDefault(camera.CameraId) > _timeProvider.GetUtcNow()) continue;
|
||||
if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = _timeProvider.GetUtcNow().AddSeconds(20);
|
||||
}
|
||||
}
|
||||
|
||||
internal static IReadOnlyDictionary<Guid, AgentCameraConfig> SelectAssignedCameras(CameraConfigStore cameras) =>
|
||||
cameras.HasCentralConfiguration
|
||||
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.RtspUrl))
|
||||
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.EffectiveRtspUrl))
|
||||
.Take(MaxPublishers).ToDictionary(c => c.CameraId)
|
||||
: new Dictionary<Guid, AgentCameraConfig>();
|
||||
|
||||
@@ -63,26 +129,26 @@ public sealed class LiveCameraRelayService(
|
||||
|
||||
private async Task<bool> StartAsync(AgentCameraConfig camera, CancellationToken ct)
|
||||
{
|
||||
var client = clients.CreateClient();
|
||||
client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", state.ApiKey);
|
||||
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",
|
||||
$"{_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<PublishSession>(cancellationToken: ct);
|
||||
if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false;
|
||||
|
||||
var start = CreateStartInfo("ffmpeg", camera.RtspUrl, destination);
|
||||
var sourceUrl = camera.EffectiveRtspUrl;
|
||||
var start = CreateStartInfo("ffmpeg", sourceUrl, destination);
|
||||
try
|
||||
{
|
||||
var process = Process.Start(start);
|
||||
var process = _processFactory.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);
|
||||
_relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30), sourceUrl);
|
||||
_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; }
|
||||
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)
|
||||
@@ -95,26 +161,20 @@ public sealed class LiveCameraRelayService(
|
||||
return start;
|
||||
}
|
||||
|
||||
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));
|
||||
if (!relay.Process.HasExited) relay.Process.KillEntireProcessTree();
|
||||
await relay.Process.WaitForExitAsync(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); }
|
||||
{ _logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); }
|
||||
finally { relay.Process.Dispose(); }
|
||||
}
|
||||
|
||||
private async Task StopAllAsync()
|
||||
internal async Task StopAllAsync()
|
||||
{
|
||||
foreach (var cameraId in _relays.Keys.ToArray()) await StopAsync(cameraId);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
using Heimdall.Agent.Services;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Agent.Tests;
|
||||
|
||||
@@ -48,6 +53,250 @@ public sealed class LiveCameraRelayServiceTests
|
||||
Assert.DoesNotContain(invalidId, selected.Keys);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Synchronize_stops_and_restarts_relay_when_source_changes_for_same_camera()
|
||||
{
|
||||
var cameraId = Guid.NewGuid();
|
||||
const string oldSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/old";
|
||||
const string newSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/new";
|
||||
var cameras = new CameraConfigStore();
|
||||
SetCameraSource(cameras, cameraId, oldSource);
|
||||
var processFactory = new FakeRelayProcessFactory();
|
||||
var logMessages = new List<string>();
|
||||
using var loggerFactory = LoggerFactory.Create(builder => builder.AddProvider(new ListLoggerProvider(logMessages)));
|
||||
var service = CreateService(cameras, processFactory, loggerFactory.CreateLogger<LiveCameraRelayService>());
|
||||
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
var first = Assert.Single(processFactory.Started);
|
||||
Assert.False(first.Process.HasExited);
|
||||
Assert.Equal(oldSource, InputSource(first.StartInfo));
|
||||
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
Assert.Single(processFactory.Started);
|
||||
Assert.False(first.Process.HasExited);
|
||||
|
||||
SetCameraSource(cameras, cameraId, newSource);
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(2, processFactory.Started.Count);
|
||||
Assert.True(first.Process.HasExited);
|
||||
Assert.True(first.Process.KilledEntireProcessTree);
|
||||
Assert.True(first.Process.WaitedForExit);
|
||||
Assert.True(first.Process.Disposed);
|
||||
var second = processFactory.Started[1];
|
||||
Assert.False(second.Process.HasExited);
|
||||
Assert.Equal(newSource, InputSource(second.StartInfo));
|
||||
var logs = string.Join('\n', logMessages);
|
||||
Assert.DoesNotContain("synthetic-secret", logs, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("synthetic-agent-key", logs, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("synthetic-publish-token", logs, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(oldSource, logs, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(newSource, logs, StringComparison.Ordinal);
|
||||
|
||||
await service.StopAllAsync();
|
||||
Assert.True(second.Process.HasExited);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Synchronize_stops_and_restarts_relay_when_substream_source_changes()
|
||||
{
|
||||
var cameraId = Guid.NewGuid();
|
||||
const string primarySource = "rtsp://127.0.0.1:18554/primary";
|
||||
const string oldSubSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/sub-old";
|
||||
const string newSubSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/sub-new";
|
||||
var cameras = new CameraConfigStore();
|
||||
SetCameraSource(cameras, cameraId, primarySource, oldSubSource);
|
||||
var processFactory = new FakeRelayProcessFactory();
|
||||
using var loggerFactory = LoggerFactory.Create(_ => { });
|
||||
var service = CreateService(cameras, processFactory, loggerFactory.CreateLogger<LiveCameraRelayService>());
|
||||
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
var first = Assert.Single(processFactory.Started);
|
||||
Assert.Equal(oldSubSource, InputSource(first.StartInfo));
|
||||
|
||||
SetCameraSource(cameras, cameraId, primarySource, newSubSource);
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(2, processFactory.Started.Count);
|
||||
Assert.True(first.Process.HasExited);
|
||||
Assert.True(first.Process.Disposed);
|
||||
Assert.Equal(newSubSource, InputSource(processFactory.Started[1].StartInfo));
|
||||
await service.StopAllAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Process_factory_kills_and_waits_for_a_child_process()
|
||||
{
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/sh",
|
||||
UseShellExecute = false,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
startInfo.ArgumentList.Add("/c");
|
||||
startInfo.ArgumentList.Add("ping -t 127.0.0.1");
|
||||
}
|
||||
else
|
||||
{
|
||||
startInfo.ArgumentList.Add("-c");
|
||||
startInfo.ArgumentList.Add("exec sleep 30");
|
||||
}
|
||||
|
||||
using var process = new LiveRelayProcessFactory().Start(startInfo);
|
||||
Assert.NotNull(process);
|
||||
try
|
||||
{
|
||||
Assert.False(process.HasExited);
|
||||
process.KillEntireProcessTree();
|
||||
await process.WaitForExitAsync(TimeSpan.FromSeconds(5));
|
||||
Assert.True(process.HasExited);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!process.HasExited)
|
||||
{
|
||||
process.KillEntireProcessTree();
|
||||
await process.WaitForExitAsync(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Synchronize_keeps_unchanged_source_until_renewal_boundary()
|
||||
{
|
||||
var cameraId = Guid.NewGuid();
|
||||
const string source = "rtsp://127.0.0.1:18554/stable";
|
||||
var cameras = new CameraConfigStore();
|
||||
SetCameraSource(cameras, cameraId, source);
|
||||
var timeProvider = new ManualTimeProvider(DateTimeOffset.UtcNow);
|
||||
var processFactory = new FakeRelayProcessFactory();
|
||||
using var loggerFactory = LoggerFactory.Create(_ => { });
|
||||
var service = CreateService(cameras, processFactory,
|
||||
loggerFactory.CreateLogger<LiveCameraRelayService>(),
|
||||
() => timeProvider.GetUtcNow().AddMinutes(8), timeProvider);
|
||||
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
var first = Assert.Single(processFactory.Started);
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
Assert.Single(processFactory.Started);
|
||||
Assert.False(first.Process.HasExited);
|
||||
|
||||
timeProvider.Advance(TimeSpan.FromMinutes(7.5));
|
||||
await service.SynchronizeAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(2, processFactory.Started.Count);
|
||||
Assert.True(first.Process.HasExited);
|
||||
Assert.False(processFactory.Started[1].Process.HasExited);
|
||||
await service.StopAllAsync();
|
||||
}
|
||||
|
||||
private static LiveCameraRelayService CreateService(
|
||||
CameraConfigStore cameras,
|
||||
ILiveRelayProcessFactory processFactory,
|
||||
ILogger<LiveCameraRelayService> logger,
|
||||
Func<DateTimeOffset>? renewAtProvider = null,
|
||||
TimeProvider? timeProvider = null)
|
||||
{
|
||||
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "synthetic-agent-key" };
|
||||
var clients = new TestHttpClientFactory(() => new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = JsonContent.Create(new
|
||||
{
|
||||
url = "rtsps://media.invalid/camera?token=synthetic-publish-token",
|
||||
renewAt = renewAtProvider?.Invoke() ?? DateTimeOffset.UtcNow.AddMinutes(8)
|
||||
})
|
||||
});
|
||||
return new LiveCameraRelayService(state,
|
||||
Options.Create(new AgentOptions { CentralUrl = "https://central.invalid" }),
|
||||
cameras, clients, processFactory, timeProvider ?? TimeProvider.System, logger);
|
||||
}
|
||||
|
||||
private sealed class ManualTimeProvider(DateTimeOffset current) : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _current = current;
|
||||
public override DateTimeOffset GetUtcNow() => _current;
|
||||
public void Advance(TimeSpan duration) => _current = _current.Add(duration);
|
||||
}
|
||||
|
||||
private static void SetCameraSource(CameraConfigStore store, Guid cameraId, string source, string? subSource = null)
|
||||
{
|
||||
var settings = new Dictionary<string, string>
|
||||
{
|
||||
[$"camera.{cameraId}.rtsp"] = source,
|
||||
[$"camera.{cameraId}.enabled"] = "true"
|
||||
};
|
||||
if (subSource is not null) settings[$"camera.{cameraId}.sub_rtsp"] = subSource;
|
||||
store.ReplaceCentral(settings);
|
||||
}
|
||||
|
||||
private static string InputSource(ProcessStartInfo startInfo)
|
||||
{
|
||||
var args = startInfo.ArgumentList.ToArray();
|
||||
return args[Array.IndexOf(args, "-i") + 1];
|
||||
}
|
||||
|
||||
private sealed class TestHttpClientFactory(Func<HttpResponseMessage> responseFactory) : IHttpClientFactory
|
||||
{
|
||||
public HttpClient CreateClient(string name) => new(new TestHttpMessageHandler(responseFactory));
|
||||
}
|
||||
|
||||
private sealed class TestHttpMessageHandler(Func<HttpResponseMessage> responseFactory) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(responseFactory());
|
||||
}
|
||||
|
||||
private sealed class FakeRelayProcessFactory : ILiveRelayProcessFactory
|
||||
{
|
||||
public List<(ProcessStartInfo StartInfo, FakeRelayProcess Process)> Started { get; } = [];
|
||||
|
||||
public ILiveRelayProcess Start(ProcessStartInfo startInfo)
|
||||
{
|
||||
var process = new FakeRelayProcess();
|
||||
Started.Add((startInfo, process));
|
||||
return process;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeRelayProcess : ILiveRelayProcess
|
||||
{
|
||||
public bool HasExited { get; private set; }
|
||||
public bool KilledEntireProcessTree { get; private set; }
|
||||
public bool WaitedForExit { get; private set; }
|
||||
public bool Disposed { get; private set; }
|
||||
|
||||
public void KillEntireProcessTree()
|
||||
{
|
||||
KilledEntireProcessTree = true;
|
||||
HasExited = true;
|
||||
}
|
||||
|
||||
public Task WaitForExitAsync(TimeSpan timeout)
|
||||
{
|
||||
WaitedForExit = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose() => Disposed = true;
|
||||
}
|
||||
|
||||
private sealed class ListLoggerProvider(List<string> messages) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new ListLogger(messages);
|
||||
public void Dispose() { }
|
||||
|
||||
private sealed class ListLogger(List<string> messages) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
|
||||
Exception? exception, Func<TState, Exception?, string> formatter) => messages.Add(formatter(state, exception));
|
||||
}
|
||||
}
|
||||
|
||||
private static string OptionValue(string[] args, string option, int occurrence = 0)
|
||||
{
|
||||
var indices = args.Select((arg, index) => (arg, index)).Where(item => item.arg == option)
|
||||
|
||||
Reference in new issue
Block a user