Author SHA1 Message Date
arnaud.dartois 96d53b201f fix(agent): restart live relay when effective source changes (#355)
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 25m55s
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 25m39s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 9m1s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
Handle primary and configured substream changes in the live relay.

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 02:16:04 +01:00
arnaud.dartois 561feb424c docs(live-view): align guides with MediaMTX WHEP (#353)
Heimdall Gitea / Detect CI scope (push) Successful in 8s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 00:32:59 +01:00
arnaud.dartois 72edf1c514 docs(signalr): align hub guide with implemented contracts (#351)
Heimdall Gitea / Detect CI scope (push) Successful in 20s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 5s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 00:22:07 +01:00
arnaud.dartois 3ef030086d Fix RustFS secret bind paths in server installers (#344)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 21m8s
Heimdall Gitea / Build and scan server image (push) Successful in 9m35s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m50s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 16m54s
Heimdall Gitea / Publish versioned installer release (push) Successful in 3m43s
Heimdall Gitea / CI policy (push) Successful in 3s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 18:02:30 +01:00
arnaud.dartois 060239d10e test(agent): validate startup dependency composition (#343)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 16:24:08 +01:00
arnaud.dartois aa5ca868db Use latest Docker images for Agent installation (#338)
Heimdall Gitea / Detect CI scope (push) Successful in 13s
Heimdall Gitea / Build and tests (push) Successful in 21m42s
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 9m1s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 5s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 15:42:42 +01:00
arnaud.dartois be1cb9b479 Fix camera config reconciliation latency
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 21m23s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 10m36s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 28m8s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 4s
Refs #157

Reconcile camera config changes immediately and strengthen the disposable toggle acceptance evidence.

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 14:37:33 +01:00
arnaud.dartois a8ce828c01 docs(backup): clarify key lifecycle and recovery measurements
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Failing after 17m25s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Failing after 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 12:51:35 +01:00
arnaud.dartois c5a250586b fix(ci): use Forgejo-supported variable for Renovate endpoint
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 17m45s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 3s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 12:17:53 +01:00
arnaud.dartois c8a428555a test(install): assert agent socket access for #293 (#333)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 23m29s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 11:26:49 +01:00
arnaud.dartois ec80e31e33 test(storage): document migration startup acceptance for #300 (#332)
Heimdall Gitea / Detect CI scope (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 11:12:37 +01:00
arnaud.dartois 511fbfce7b fix(install): rendre les secrets RustFS et coturn lisibles (#331)
Heimdall Gitea / CI policy (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Successful in 22m34s
Heimdall Gitea / Detect CI scope (push) Successful in 8s
Heimdall Gitea / Build and scan server image (push) Successful in 7m54s
Heimdall Gitea / Build and scan agent image (push) Successful in 13m51s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 26m57s
Heimdall Gitea / Publish versioned installer release (push) Successful in 6m47s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-12 06:34:19 +01:00
40 changed files with 1656 additions and 566 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
image: renovate/renovate:44.133.0
env:
RENOVATE_PLATFORM: gitea
RENOVATE_ENDPOINT: ${{ vars.GITEA_API_ENDPOINT }}
RENOVATE_ENDPOINT: ${{ vars.FORGEJO_API_ENDPOINT }}
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_ONBOARDING: 'false'
steps:
+52
View File
@@ -150,6 +150,58 @@ ne sont pas supprimés. L’archive contient le répertoire `dp-keys`, dont
`dp-cert.pfx` protège les clés Data Protection. Protéger les sauvegardes locales
et S3 comme des données sensibles.
### Conservation et rotation des clés Data Protection
Le volume Central contient le trousseau XML Data Protection et `dp-cert.pfx`,
qui protège ces clés au repos. L’archive de données protégées doit conserver
l’ensemble de `dp-keys`; restaurer PostgreSQL sans ce répertoire peut laisser
les identifiants et autres charges utiles protégées impossibles à relire.
- Arrêter Central avant la restauration et restaurer l’archive protégée complète
dans le volume correspondant. Ne remplacer ni supprimer `dp-cert.pfx` ou des
fichiers de clés indépendamment.
- Garder les archives comme des secrets : `dp-cert.pfx` contient la clé privée
qui déchiffre le trousseau. Le script crée l’archive locale avec le mode
`0600`; contrôler aussi les permissions et l’accès du bucket S3.
- Le framework fait évoluer automatiquement le trousseau selon sa politique de
durée de vie. Les clés expirées restent nécessaires pour lire les données
protégées avec ces clés; ne pas purger les anciennes clés au seul motif
qu’elles ont expiré.
- Le certificat de protection `dp-cert.pfx` n’a pas de procédure de rotation
manuelle validée dans Heimdall. Ne pas le remplacer lors d’une restauration.
Toute rotation planifiée doit faire l’objet d’une procédure séparée et d’un
essai sur copie isolée, avec vérification de lecture des anciennes et nouvelles
charges utiles avant suppression de la clé précédente.
Voir [la gestion des clés Data Protection dans ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-management)
pour le cycle des clés; supprimer une clé qui protège encore des données rend
ces données définitivement illisibles.
### Mesure RPO/RTO
Les horaires configurés ne constituent pas une mesure de RPO. Les sauvegardes
PostgreSQL et du volume protégé sont prises séparément, et le miroir RustFS suit
un autre intervalle; Heimdall ne fournit pas de point de restauration atomique.
Le responsable d’exploitation doit définir les objectifs visés et le scénario
avant un exercice réel.
Pour chaque exercice autorisé, consigner sans données personnelles :
1. La date UTC du changement connu le plus récent dans chaque stockage, la date
de la panne simulée, et la date du changement le plus récent réellement
restauré. Calculer le RPO séparément pour PostgreSQL, objets locaux/S3 et
clés protégées; retenir le pire résultat pour le service.
2. L’heure de début de la restauration, ses jalons (base, objets, démarrage de
Central) et l’heure où les vérifications post-restauration réussissent. Cette
durée est le RTO mesuré pour cet essai, pas un engagement universel.
3. Versions des scripts/images, tailles et nombres d’objets, hôte/CPU/mémoire,
stockage et réseau utilisés, étapes manuelles, erreurs et résultat final.
Répéter l’exercice complet au moins deux fois avant de fixer une cible.
La recette synthétique de `test-backup-restore.sh` ne comprend pas le démarrage
de Central, une connexion utilisateur ni un backend S3; son temps d’exécution
ne doit jamais être présenté comme un RTO de production.
## Test de restauration (runbook)
### Prérequis
+1 -1
View File
@@ -39,7 +39,7 @@ L’installateur Linux est servi par Central avec son superviseur. Il installe l
Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution.
Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
Pour un Agent Docker, le Compose et les commandes `docker run` générés par l’IHM installent le dépôt d’image avec le tag `latest`; Compose et `docker run` vérifient le registre au démarrage. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. Pour les mises à jour déclenchées ensuite par Central, l’Agent vérifie la signature et le digest d’image du manifeste signé avant de remplacer le conteneur. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
## Rotation
+9 -7
View File
@@ -1,8 +1,8 @@
# Docker Compose deployment
The required stack is PostgreSQL and Heimdall Central. The Agent is deployed
separately on each camera-network host; the Central UI supplies a
digest-pinned Agent Compose file for each site. RustFS, ntfy, Ollama, TURN,
separately on each camera-network host; the Central UI supplies an Agent
Compose file using the `latest` tag for each site. RustFS, ntfy, Ollama, TURN,
Redis and scheduled backups have separate Compose files and can be left out.
## Central and database
@@ -135,11 +135,13 @@ in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-ac
## Agent
Prefer the Compose shown in the Central UI's site installation panel. It uses
the image reference and digest from Central's verified release manifest and
includes the site token, public Central URL, Agent name and release public key.
Save it as `docker-compose.yml`, then run `docker compose up -d`. The generated
Compose contains the pinned trust key; no separate PEM file is required. Do
not substitute a mutable image tag for the digest.
the Agent image's `latest` tag and includes the site token, public Central URL,
Agent name and release public key. Compose uses `pull_policy: always` so an
explicit `docker compose up` checks for the latest image. Save it as
`docker-compose.yml`, then run `docker compose up -d`. The generated Compose
contains the pinned trust key; no separate PEM file is required. Updates
dispatched later by Central continue to verify the digest in the signed release
manifest before replacing the running container.
The Agent Compose is generated by Central's UI for the selected site; there is
no production Agent Compose in this repository. For local development only,
+1 -1
View File
@@ -8,7 +8,7 @@ Les jobs exigent `runs-on: [ubuntu-latest, build-agent]`. Déclarer `build-agent
Chaque runner lit sa configuration au démarrage. Ne pas rediriger `sources.tordais.cc` vers `host-gateway` dans `container.options` : cela a empêché les checkouts. Le workflow ne publie pas de rapports comme artefacts distants : les fichiers `artifacts/` sont utilisés dans le job (par exemple pour le seuil de couverture), puis disparaissent avec celui-ci. Le run historique #442 a signalé `CreateArtifact: EHOSTUNREACH`; aucun job courant ne dépend du service artefacts pour réussir.
Le workflow Renovate lit l’API Gitea dans la variable d’action `GITEA_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Avant de démarrer Renovate, il vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
Le workflow Renovate lit l’API Forgejo dans la variable d’action `FORGEJO_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Forgejo réserve les noms de variables commençant par `GITEA_`. Avant de démarrer Renovate, le workflow vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
`scripts/ci/cleanup-docker.sh` journalise l'espace et élimine avant/après les builds les anciennes images Heimdall, les volumes Trivy abandonnés, les couches de build inutilisées depuis plus de 30 minutes et les images pendantes. Il ne purge pas les volumes, réseaux ou images nommées des autres projets. Le run #194 sur `runner-odin` a récupéré 95,89 Go avant build et 7,703 Go après job ; les 1 965 tests, deux images et scans ont réussi.
+76 -420
View File
@@ -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)
+34 -22
View File
@@ -22,7 +22,7 @@ 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
- Live vidéo : relais RTSP de l’Agent vers MediaMTX, lecture navigateur WHEP/WebRTC; mesurer la latence avant d’annoncer une cible
- IA locale : ONNX Runtime (GPU sur agents équipés, mutualisable inter-sites) + Ollama (LLM résumés)
- Espace utilisateur : Admin (global) + User (site-scope)
- Stockage : RustFS/S3 centralisé
@@ -40,16 +40,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 / IA │ │
│ │ REST + │ │ Blazor │ │ Hangfire │ │ Ollama / 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,15 +57,17 @@ 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
```
---
@@ -131,25 +133,35 @@ Enum: GpuAcceleration, ThemeMode
- 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.
Un changement d’URL source pour le même CameraId peut conserver l’ancien relay
jusqu’au renouvellement; cette limite Agent est suivie dans #355.
## 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`
@@ -181,7 +193,7 @@ Voir `docs/hangfire-usage.md` pour le code complet de chaque job.
- MudBlazor, Interactive Server Rendering
- 8 pages : Login, Dashboard, Sites, Cameras, Persons, Events, Admin, Alertes
- Live vidéo via module JS autonome (WebRTC)
- 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
@@ -202,12 +214,12 @@ 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)
mediamtx: # Serveur média RTSP/WHEP (optionnel, live vidéo)
coturn: # TURN relay (optionnel, double NAT)
```
+27 -31
View File
@@ -281,7 +281,7 @@ Lancer
└──────────────────────────────────────────────┘
```
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi une référence d'image vérifiée par digest. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi les métadonnées d'image vérifiées de la release, puis installe l'image publiée avec le tag `latest`; les remplacements déclenchés par Central restent vérifiés par digest signé. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
### États — Détail Site
@@ -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
+2 -1
View File
@@ -350,6 +350,7 @@ if ($startCore) {
}
foreach ($service in $selected) {
$composeProjectDirectory = if ($service -eq 'backup') { $optionalDirectory } else { $destination }
switch ($service) {
'rustfs' {
$accessKeyPath = Join-Path $optionalSecretsDirectory 'rustfs_access_key'
@@ -379,7 +380,7 @@ foreach ($service in $selected) {
}
}
if ($startCore -and (Read-YesNo "Démarrer le service optionnel $service ?" 'o')) {
Invoke-DockerCompose @('--project-name', "heimdall-$service", '--env-file', $envPath,
Invoke-DockerCompose @('--project-directory', $composeProjectDirectory, '--project-name', "heimdall-$service", '--env-file', $envPath,
'-f', (Join-Path $optionalDirectory "docker-compose.$service.yml"), 'up', '-d')
} else {
Write-Host "Service $service préparé dans $optionalDirectory."
+6 -1
View File
@@ -296,6 +296,10 @@ if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO
fi
for service in "${selected[@]}"; do
compose_project_directory="$destination"
if [[ "$service" == backup ]]; then
compose_project_directory="$destination/optional"
fi
case "$service" in
rustfs)
printf '%s' "heimdall$(openssl rand -hex 8)" > "$destination/optional/secrets/rustfs_access_key"
@@ -318,7 +322,8 @@ for service in "${selected[@]}"; do
;;
esac
if [[ "$start_core" == yes ]] && [[ "$(ask "Démarrer le service optionnel ${service} ?" 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
docker compose --project-name "heimdall-${service}" --env-file "$destination/.env" \
docker compose --project-directory "$compose_project_directory" --project-name "heimdall-${service}" \
--env-file "$destination/.env" \
-f "$destination/optional/docker-compose.${service}.yml" up -d
else
say "Service ${service} préparé dans $destination/optional/."
+1 -1
View File
@@ -87,7 +87,7 @@ Windows, copiez la commande affichée sur l’hôte distant : elle télécharge
script depuis le Central et l’exécute avec les identifiants propres à ce site.
L’installation Linux peut créer un service systemd; l’installation Windows
peut créer un service Windows (PowerShell administrateur requis). Pour Docker,
utilisez le Compose généré par l’IHM, épinglé au digest signé. Aucun fichier de
utilisez le Compose généré par l’IHM, qui suit le tag `latest`. Aucun fichier de
clé ni Compose de production ne doit être copié depuis le dépôt. Voir le
[guide de signature et de mise à jour Agent](docs/agent-release-signing.md).
Le Compose Docker monte le socket Docker de l’hôte pour permettre les mises à
+3 -3
View File
@@ -9,12 +9,12 @@ export function validateEndpoint(value) {
try {
parsed = new URL(value);
} catch {
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
}
if (parsed.protocol !== 'https:' || parsed.username || parsed.password ||
parsed.search || parsed.hash || !parsed.pathname.replace(/\/$/, '').endsWith('/api/v1')) {
throw new Error('GITEA_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
}
return parsed.href.replace(/\/$/, '');
@@ -38,7 +38,7 @@ export async function checkGiteaAccess(apiEndpoint, accessToken, fetchImpl = fet
if (!response.ok) {
const detail = response.status === 401 || response.status === 403
? 'Check that RENOVATE_TOKEN is active and has repository read and write access.'
: 'Check GITEA_API_ENDPOINT and the Gitea API availability.';
: 'Check FORGEJO_API_ENDPOINT and the Forgejo API availability.';
throw new Error(`Gitea API preflight failed with HTTP ${response.status}. ${detail}`);
}
}
+2 -2
View File
@@ -2,13 +2,13 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { checkGiteaAccess, validateEndpoint } from './renovate-preflight.mjs';
test('accepts an HTTPS Gitea API endpoint and trims its trailing slash', () => {
test('accepts an HTTPS Forgejo API endpoint and trims its trailing slash', () => {
assert.equal(validateEndpoint('https://forge.example/api/v1/'), 'https://forge.example/api/v1');
});
test('rejects non-HTTPS, malformed, and non-API endpoints', () => {
for (const value of ['http://forge.example/api/v1', 'https://forge.example/', 'not a URL']) {
assert.throws(() => validateEndpoint(value), /HTTPS URL ending in \/api\/v1/);
assert.throws(() => validateEndpoint(value), /FORGEJO_API_ENDPOINT.*HTTPS URL ending in \/api\/v1/);
}
});
+12
View File
@@ -73,6 +73,18 @@ class PublicationWorkflowTests(unittest.TestCase):
self.assertNotIn('secrets.GITEA_TOKEN', workflow.split(' publish:\n', 1)[0])
class PowerShellInstallerTests(unittest.TestCase):
def test_optional_compose_commands_resolve_paths_from_install_root(self):
linux_installer = (REPO_ROOT/'install/install-server.sh').read_text()
windows_installer = (REPO_ROOT/'install/install-server.ps1').read_text()
self.assertIn('compose_project_directory="$destination"', linux_installer)
self.assertIn('compose_project_directory="$destination/optional"', linux_installer)
self.assertIn('docker compose --project-directory "$compose_project_directory"',
linux_installer)
self.assertIn("$composeProjectDirectory = if ($service -eq 'backup') { $optionalDirectory } else { $destination }",
windows_installer)
self.assertIn("Invoke-DockerCompose @('--project-directory', $composeProjectDirectory,",
windows_installer)
@unittest.skipUnless(shutil.which('pwsh'), 'PowerShell is not installed')
def test_server_installer_has_valid_powershell_syntax(self):
parser = "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'install/install-server.ps1'), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 }"
+38
View File
@@ -0,0 +1,38 @@
---
name: agent-startup-composition
description: Validate Heimdall Agent dependency-injection composition by starting its source-built container without a Central dependency.
---
# Agent startup composition
`src/Heimdall.Agent/Program.cs` constructs `SnapshotPipelineServiceOptions` in
the service-registration factory before registering the hosted service. Do not
register `SnapshotPipelineService` with the generic `AddHostedService<T>()`
unless every constructor dependency, including that options record, is
registered in DI. A missing dependency can prevent `Host.StartAsync` and leave
the Agent container unable to start.
## Acceptance
Run `bash skills/agent-startup-composition/acceptance.sh` from the repository
root. The recipe builds only the CPU Agent image from the current checkout with
a unique local tag and starts it in a disposable Compose project with generated
site-token data and an internal-only network. Its Central URL points to the
Agent container's own unused loopback port; it cannot reach a deployment.
The recipe proves that:
1. The Agent host starts and remains running with its production service
registrations, including `SnapshotPipelineService`.
2. `/health/live` responds successfully before registration with Central; the
readiness endpoint `/healthz` is intentionally not used because it reports
Unhealthy until Central registration succeeds.
3. Startup logs do not contain the missing
`SnapshotPipelineServiceOptions` dependency or a host-start failure.
4. Cleanup removes the exact Compose project, generated state volume/network,
and this recipe's one exact Agent image tag, then verifies their absence.
This checks DI and host startup only. It does not validate Central registration,
camera discovery, model inference, a published Agent, or a deployed installation.
The EXIT trap preserves the test result, attempts each cleanup independently,
and reports cleanup failures. The Dockerfile's shared .NET base images remain.
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env bash
set -Eeuo pipefail
repo_root=$(git rev-parse --show-toplevel)
project="heimdall-agent-startup-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 3)"
image_tag="heimdall-agent:${project}-agent"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
compose_file="$temp_dir/compose.yaml"
local_image_tags=("$image_tag")
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
containers=
volumes=
networks=
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
if docker image inspect "$tag" >/dev/null 2>&1; then
cleanup_failed=1
fi
done
rm -f -- "$env_file" "$compose_file" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable Agent startup cleanup failed for project %s\n' "$project" >&2
status=1
else
printf 'Cleanup verified: project=%s; containers/volumes/networks absent; image tag %s absent.\n' \
"$project" "$image_tag"
fi
exit "$status"
}
trap cleanup EXIT
umask 077
cat >"$env_file" <<EOF
PROJECT=$project
SOURCE_ROOT=$repo_root
IMAGE_TAG=$image_tag
SYNTHETIC_SITE_TOKEN=$(openssl rand -hex 32)
EOF
cat >"$compose_file" <<'EOF'
services:
agent:
image: ${IMAGE_TAG}
build:
context: ${SOURCE_ROOT}
dockerfile: docker/Dockerfile.agent
network: host
restart: "no"
environment:
Agent__CentralUrl: http://127.0.0.1:1
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${SYNTHETIC_SITE_TOKEN}
Agent__AgentName: ${PROJECT}
Agent__RegistrationMaxRetries: "20"
Agent__HeartbeatIntervalSeconds: "5"
Agent__DiscoveryEnabled: "false"
Agent__UpdateCheckIntervalHours: "0"
Agent__StateDirectory: /var/lib/heimdall
Sentry__Dsn: ""
volumes:
- agent_state:/var/lib/heimdall
networks:
- isolated
volumes:
agent_state:
networks:
isolated:
internal: true
EOF
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
up --build --detach agent
container_id=$(docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps -q agent)
[[ -n "$container_id" ]] || { printf 'Agent container was not created.\n' >&2; exit 1; }
deadline=$((SECONDS + 90))
live_ready=0
while (( SECONDS < deadline )); do
running=$(docker inspect --format '{{.State.Running}}' "$container_id" 2>/dev/null || true)
if [[ "$running" != true ]]; then
printf 'Agent container exited before its live endpoint became ready.\n' >&2
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" ps >&2 || true
exit 1
fi
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" \
exec -T agent wget -q --tries=1 --spider http://127.0.0.1:8080/health/live >/dev/null 2>&1; then
live_ready=1
break
fi
sleep 1
done
(( live_ready == 1 )) || { printf 'Agent /health/live did not become ready.\n' >&2; exit 1; }
restart_count=$(docker inspect --format '{{.RestartCount}}' "$container_id")
[[ "$restart_count" == 0 ]] || { printf 'Agent container restarted unexpectedly.\n' >&2; exit 1; }
if docker compose -p "$project" --env-file "$env_file" -f "$compose_file" logs agent 2>&1 |
rg -q "Unable to resolve service for type 'Heimdall\.Agent\.Services\.SnapshotPipelineServiceOptions'|Hosting failed to start"; then
printf 'Agent startup log contains a dependency-injection or host-start failure.\n' >&2
exit 1
fi
printf 'Agent host started; /health/live returned success; container remained running without restart.\n'
printf 'Project: %s\nLocal image tag: %s\n' "$project" "$image_tag"
+2 -1
View File
@@ -13,6 +13,7 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
- PostgreSQL backups use `docker/scripts/backup.sh` and restores use `restore.sh`. Supply credentials through a generated `POSTGRES_PASSWORD_FILE` or a generated environment file; never reuse `docker/.env`, production secrets, or live volumes.
- `backup-protected-data.sh` archives the Central data volume, including local objects and `dp-keys`. Restore with `restore-protected-data.sh` only while Central is stopped. The script overlays files and deliberately keeps unrelated target files.
- 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.
- `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.
@@ -21,7 +22,7 @@ Use this workflow when changing `docker/scripts/backup*.sh`, `docker/scripts/res
1. Read `docker/backup/README.md` and `docker/scripts/test-backup-restore.sh` before changing the flow.
2. Run the script and require all assertions to pass, including row/FK integrity, object/key digests, and Data Protection key permissions.
3. For changes to volume-level restore or Compose behavior, build a disposable Compose project from the checkout with unique project name, generated credentials, and generated named volumes. Dump from one PostgreSQL volume and restore into a different volume; check a known row. Archive and remove synthetic files from the protected volume, restore them, and compare digests and key permissions.
4. Measure only the synthetic restore duration and label it as a local fixture measurement. Do not present it as a production RTO. Derive the configured backup interval separately; do not imply it is a measured production RPO.
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.
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.
+13 -2
View File
@@ -14,6 +14,7 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
- `SnapshotPipelineService` reconciles configuration on `CameraConfigStore.Changed`, while retaining a one-second config-change poll and the existing 30-second full resync as recovery. Coalesce notifications and ensure there is only one waiter on the config signal.
- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled.
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
@@ -31,6 +32,8 @@ These tests cover session idempotence, process termination, and synchronization
## Central + Agent disposable acceptance
Run `skills/camera-toggle-acceptance/acceptance.sh` from the repository root. It builds both application images from source, bootstraps synthetic Central/site/camera data, registers the real Agent container, repeats three ON/OFF cycles, checks the OFF PID bound, restarts Agent and Central while OFF, correlates the final applied config digest, and verifies exact project/tag cleanup in its EXIT trap.
- Build Central and Agent from this checkout with unique tags recorded before the first build. Retain upstream Postgres, MediaMTX, FFmpeg, SDK and ASP.NET base images.
- Use a fresh project-scoped database, JWT/site credentials, loopback-only Central/Postgres ports, network and volumes. Add a project network Agent and a synthetic MediaMTX RTSP publisher. Do not use host networking or real camera credentials.
- Bootstrap a synthetic Admin/site, create a camera pointed at the synthetic RTSP path, register the actual Agent container with the generated site token, and assign the camera to that Agent.
@@ -46,7 +49,7 @@ This acceptance proves the source-built Central/Agent software lifecycle with a
- Do not count `docker top` output when the runtime's `top` implementation differs. Prefer an in-container process identity check (`/proc/*/comm` equals `ffmpeg`) and ensure the inspection process cannot match itself. A shell command line containing the text `ffmpeg` creates a false positive if the check scans all command lines.
- Before asserting lifecycle timing, first confirm Agent `Online`, persisted camera assignment, effective config enabled value and version, and `LastAppliedCameraConfigVersion` acknowledgement. A failed precondition is not an OFF/ON timing result.
- On failed acceptance, collect sanitized Central, Agent, RTSP server and publisher diagnostics before the cleanup trap runs. Then verify project resource counts and exact image tags as described above.
- Current disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but have not yet proved toggle timing or restart persistence. Treat #59/#199 as open until a corrected process measurement completes the whole cycle.
- Earlier disposable attempts proved bootstrap, registration, assignment and Disabled config acknowledgement, but did not prove toggle timing or restart persistence. The completed source-built run below supersedes those incomplete attempts; physical camera and deployed-host validation remain external.
## Latest source-built run
@@ -54,7 +57,15 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel
## Sixth source-built run
The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold.
The sixth historical run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound and did not run restart-OFF acceptance. The subsequent 2026-11-12 acceptance below supersedes that incomplete result for current source.
## Immediate config reconciliation regression test
`SnapshotPipelineServiceTests.CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync` starts the pipeline, lets its initial synchronization complete, then changes the Central snapshot and requires the assigned camera's Error report (FFmpeg deliberately unavailable) within 500ms. This proves event-driven reconciliation ahead of the one-second config-change poll and 30-second full resync; it does not prove process termination or the full camera lifecycle. Run it with the focused camera stream suite before Compose acceptance.
## Source-built acceptance — 2026-11-12
`acceptance.sh` passed with project `heimdall-157-1794488199-31533`, Central tag `heimdall:heimdall-157-1794488199-31533-central`, and Agent tag `heimdall-agent:heimdall-157-1794488199-31533-agent`. Central and PostgreSQL published only on `127.0.0.1`. After confirming the ON config digest ACK, it exercised three ON/OFF cycles with FFmpeg release at 1,386ms, 555ms, and 410ms, then a final OFF at 810ms before restart. Each transition verified the exact Central config digest ACK and expected `camera.<id>.enabled` value. The process monitor rejected counts above one. After Agent restart while OFF, the same Agent reported Online with a heartbeat and config ACK timestamp newer than the Compose restart command's return; after Central restart it again reported Online with a fresh ACK for the persisted Disabled digest newer than the restart command's return. Agent restart while ON preserved its identity and resumed capture. Cleanup verified zero project containers, volumes, and networks and absence of both exact local image tags. This is synthetic source-built software evidence, not camera hardware or deployed-host timing.
## Camera status contract acceptance
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
stamp="$(date +%s)-$RANDOM"
project="heimdall-157-${stamp}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
env_file="$temp_dir/acceptance.env"
env_next="$temp_dir/acceptance.env.next"
compose_override="$temp_dir/compose.override.yml"
config_headers="$temp_dir/config.headers"
config_body="$temp_dir/config.json"
stage=setup
local_image_tags=("heimdall:${project}-central" "heimdall-agent:${project}-agent")
compose_files=(-f "$root/docker/docker-compose.yml" -f "$compose_override")
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
if (( status != 0 )); then
printf 'acceptance failed at stage=%s\n' "$stage" >&2
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" logs --timestamps --no-color --tail 250 heimdall-agent 2>/dev/null |
grep -E 'Config update received: config\.invalidated|Full configuration fetched successfully|Stream stopped for camera|camera config ACK' | tail -40 || true
fi
docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
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 -- "$env_file" "$env_next" "$compose_override" "$config_headers" "$config_body" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'cleanup verification failed for %s\n' "$project" >&2
status=1
else
printf 'cleanup verified: project resources absent; exact local tags absent\n'
fi
exit "$status"
}
port=$((20000 + RANDOM % 20000))
pg_port=$((port + 1))
db_password=$(openssl rand -hex 24)
jwt_key=$(openssl rand -hex 48)
jwt_refresh=$(openssl rand -hex 48)
cat >"$env_file" <<EOF
POSTGRES_DB=heimdall_acceptance
POSTGRES_USER=acceptance
POSTGRES_PASSWORD=$db_password
POSTGRES_PORT=127.0.0.1:$pg_port
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall_acceptance;Username=acceptance;Password=$db_password
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$jwt_refresh
JWT__ISSUER=heimdall-acceptance
JWT__AUDIENCE=heimdall-acceptance-api
WEB_PORT=127.0.0.1:$port
ACCEPTANCE_PROJECT=$project
DOCKER_GID=0
HEIMDALL_NETWORK_NAME=${project}-network
HEIMDALL_TEST_SITE_TOKEN=placeholder-token
EOF
cat >"$compose_override" <<'EOF'
services:
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
heimdall-agent:
image: heimdall-agent:${ACCEPTANCE_PROJECT}-agent
build:
context: ..
dockerfile: docker/Dockerfile.agent
user: "1654:1654"
environment:
Agent__CentralUrl: http://heimdall:8080
Agent__AllowInsecureHttp: "true"
Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:?token required}
Agent__AgentName: camera-157-agent
Agent__HeartbeatIntervalSeconds: "5"
Agent__StateDirectory: /var/lib/heimdall
Agent__DiscoveryEnabled: "false"
volumes:
- agent_state:/var/lib/heimdall
depends_on:
heimdall:
condition: service_healthy
synthetic-camera-publisher:
condition: service_started
networks:
- heimdall-net
synthetic-camera:
image: bluenviron/mediamtx:1.21.3
volumes:
- ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro
networks:
- heimdall-net
synthetic-camera-publisher:
image: jrottenberg/ffmpeg:7.1-alpine
entrypoint: ["/bin/sh", "-c"]
command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 1; done"]
depends_on:
- synthetic-camera
networks:
- heimdall-net
volumes:
agent_state:
EOF
# The cleanup trap is installed before any image build or Compose start.
trap cleanup EXIT
chmod 600 "$env_file"
api="http://127.0.0.1:$port"
compose() { docker compose -p "$project" --env-file "$env_file" "${compose_files[@]}" "$@"; }
contract_failures=0
wait_http() {
for _ in $(seq 1 90); do
if curl -fsS --max-time 2 "$api/healthz" >/dev/null 2>&1; then return 0; fi
sleep 2
done
return 1
}
request() { curl -fsS --max-time 10 -H "Authorization: Bearer $admin_token" -H 'Content-Type: application/json' "$@"; }
ffmpeg_count() {
compose exec -T heimdall-agent sh -c 'n=0; for f in /proc/[0-9]*/comm; do IFS= read -r p < "$f" || continue; [ "$p" = ffmpeg ] && n=$((n+1)); done; printf "%s\n" "$n"'
}
wait_count() {
expected=$1; seconds=$2
for _ in $(seq 1 "$((seconds * 20))"); do
count=$(ffmpeg_count)
observed_at_ns=$(date +%s%N)
(( count <= 1 )) || return 1
if [[ "$count" == "$expected" ]]; then
count_observed_at_ns=$observed_at_ns
return 0
fi
sleep 0.05
done
return 1
}
wait_ack() {
expected_enabled=$1
for _ in $(seq 1 100); do
request -D "$config_headers" "$api/api/settings/agent/$agent_id" >"$config_body"
wanted=$(awk 'BEGIN{IGNORECASE=1} /^X-Camera-Config-Version:/ {gsub("\r", "", $2); print $2}' "$config_headers")
actual_enabled=$(jq -r --arg key "camera.$camera_id.enabled" '.[$key] // empty' "$config_body")
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
applied=$(jq -r "[.items[]? | select(.id==\"$agent_id\")][0].lastAppliedCameraConfigVersion // empty" <<<"$agents")
if [[ -n "$wanted" && "$wanted" == "$applied" && "$actual_enabled" == "$expected_enabled" ]]; then
acknowledged_version=$wanted
return 0
fi
sleep 0.1
done
return 1
}
wait_agent_reconnected_and_ack() {
restarted_at_ns=$1
expected_version=$2
for _ in $(seq 1 60); do
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
agent=$(jq -cer "[.items[]? | select(.id==\"$agent_id\")][0]" <<<"$agents")
status=$(jq -r '.status // empty' <<<"$agent")
heartbeat=$(jq -r '.lastHeartbeat // empty' <<<"$agent")
applied_version=$(jq -r '.lastAppliedCameraConfigVersion // empty' <<<"$agent")
applied_at=$(jq -r '.lastAppliedCameraConfigAt // empty' <<<"$agent")
if [[ "$status" == Online && -n "$heartbeat" && -n "$applied_at" && "$applied_version" == "$expected_version" ]]; then
heartbeat_ns=$(date -u -d "$heartbeat" +%s%N)
applied_at_ns=$(date -u -d "$applied_at" +%s%N)
if (( heartbeat_ns > restarted_at_ns && applied_at_ns > restarted_at_ns )); then
return 0
fi
fi
sleep 1
done
return 1
}
printf 'project=%s central_tag=%s agent_tag=%s\n' "$project" "${local_image_tags[0]}" "${local_image_tags[1]}"
stage=build
compose build heimdall heimdall-agent
stage=central-startup
compose up -d postgresql heimdall
wait_http
stage=bootstrap
admin_password="Tst!$(openssl rand -hex 20)A9"
bootstrap=$(curl -fsS --max-time 10 -H 'Content-Type: application/json' -d "{\"email\":\"admin-${stamp}@heimdall.test\",\"password\":\"$admin_password\",\"displayName\":\"Acceptance Admin\"}" "$api/api/auth/bootstrap-admin")
admin_token=$(jq -er '.accessToken' <<<"$bootstrap")
printf 'synthetic Admin bootstrap accepted\n'
site=$(request -X POST -d '{"name":"Camera toggle acceptance","timezone":"UTC"}' "$api/api/sites")
site_id=$(jq -er '.id' <<<"$site")
printf 'synthetic site created\n'
site_token=$(request -X POST "$api/api/sites/$site_id/tokens" | jq -er '.token')
grep -v '^HEIMDALL_TEST_SITE_TOKEN=' "$env_file" >"$env_next"
printf 'HEIMDALL_TEST_SITE_TOKEN=%s\n' "$site_token" >>"$env_next"
mv "$env_next" "$env_file"
camera=$(request -X POST -d "{\"siteId\":\"$site_id\",\"name\":\"Synthetic camera\",\"rtspUrl\":\"rtsp://synthetic-camera:8554/synthetic\"}" "$api/api/cameras")
camera_id=$(jq -er '.id' <<<"$camera")
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
printf 'synthetic camera created\n'
stage=agent-startup
compose up -d synthetic-camera synthetic-camera-publisher heimdall-agent
agent_id=
for _ in $(seq 1 60); do
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
agent_id=$(jq -r '[.items[]? | select(.name=="camera-157-agent")][0].id // empty' <<<"$agents")
[[ -n "$agent_id" ]] && break
sleep 1
done
[[ -n "$agent_id" ]]
printf 'Agent registered\n'
request -X POST -d "{\"cameraId\":\"$camera_id\",\"agentId\":\"$agent_id\",\"reason\":\"synthetic acceptance\"}" "$api/api/assignments" >/dev/null
stage=initial-on
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
wait_count 1 10
wait_ack true
off_once() {
started=$(date +%s%N)
result=$(request -X POST "$api/api/cameras/$camera_id/toggle-status")
response_ms=$((( $(date +%s%N) - started ) / 1000000))
[[ $(jq -r '.status' <<<"$result") == Disabled ]]
within_contract=1
if ! wait_count 0 2; then
within_contract=0
wait_count 0 10 || return 1
fi
elapsed_ms=$((( count_observed_at_ns - started ) / 1000000))
printf 'OFF API response=%sms; process release=%sms; under-2s=%s\n' "$response_ms" "$elapsed_ms" "$within_contract"
if (( ! within_contract || elapsed_ms >= 2000 )); then
contract_failures=$((contract_failures + 1))
fi
wait_ack false
}
for iteration in 1 2 3; do
stage="cycle-${iteration}-off"
off_once
stage="cycle-${iteration}-on"
request -X POST "$api/api/cameras/$camera_id/toggle-status" >/dev/null
wait_count 1 10
wait_ack true
count=$(ffmpeg_count)
[[ "$count" == 1 ]]
done
stage=agent-restart-on
compose restart heimdall-agent
wait_count 1 10
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
[[ "$old_agent_id" == "$agent_id" ]]
wait_ack true
stage=final-off
off_once
agents=$(request "$api/api/agents/by-site/$site_id?page=1&pageSize=20")
old_agent_id=$(jq -er '[.items[]? | select(.name=="camera-157-agent")][0].id' <<<"$agents")
compose restart heimdall-agent
post_off_restart_returned_ns=$(date +%s%N)
wait_count 0 10
wait_agent_reconnected_and_ack "$post_off_restart_returned_ns" "$acknowledged_version"
stage=central-restart-off
compose restart heimdall
central_restart_returned_ns=$(date +%s%N)
wait_http
sleep 2
[[ $(ffmpeg_count) == 0 ]]
camera=$(request "$api/api/cameras/$camera_id")
[[ $(jq -r '.status' <<<"$camera") == Disabled ]]
wait_ack false
wait_agent_reconnected_and_ack "$central_restart_returned_ns" "$acknowledged_version"
printf 'restart OFF persisted; camera config digest acknowledged\n'
if (( contract_failures > 0 )); then
printf 'contract failures=%s\n' "$contract_failures" >&2
exit 1
fi
+2 -2
View File
@@ -19,7 +19,7 @@ For installer, Compose, image, and documentation work that can proceed independe
- Optional Agent public-IP discovery has no built-in provider hostname; configure `Agent:PublicIpResolverUrl` with an HTTPS endpoint or leave it empty to report no public IP. Validate the URL before creating the HTTP client.
- Server-side API calls from Blazor circuits must prefer the process's Kestrel loopback binding over a retained browser `Host`; a public reverse-proxy host may not be reachable from inside the Central container. Normalize wildcard Kestrel binds (`0.0.0.0`, `[::]`, and `+`) to loopback while preserving the bound port.
- Installer scripts should embed the official Heimdall source base as their standalone default and allow `HEIMDALL_SOURCE_BASE_URL` to override it for reviewed revisions or mirrors. Use it only for Heimdall-owned source assets; keep vendor dependencies on their official distribution sources.
- Configure the Gitea API endpoint used by Renovate through the Actions variable `GITEA_API_ENDPOINT`; do not embed the forge hostname in workflow YAML. Track credential/run validation in its Gitea issue.
- Configure the Forgejo API endpoint used by Renovate through the Actions variable `FORGEJO_API_ENDPOINT`; Forgejo reserves variable names beginning with `GITEA_`. Do not embed the forge hostname in workflow YAML. Track credential/run validation in its Gitea issue.
- Keep Compose network names project-scoped by omitting a fixed `networks.*.name`, especially for disposable validation projects.
## Deployment behavior
@@ -45,7 +45,7 @@ For installer, Compose, image, and documentation work that can proceed independe
## Acceptance
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
Run `bash -n install/install-server.sh`, validate PowerShell syntax when `pwsh` is available, and run `docker compose config --quiet` for both the installer output and `docker/docker-compose.prod.yml`. Exercise a first install and a second run against an isolated temporary directory: confirm secrets and nondefault `.env` values are byte-for-byte unchanged, the old Compose is backed up, missing new variables are added once, and no volume removal command appears. For the Site Install UI, assert generated CPU/GPU Compose and `docker run` references use the corresponding `:latest` Agent image, Compose sets `pull_policy: always`, Docker Run commands set `--pull always`, all paths mount `/var/run/docker.sock`, and the non-root Agent receives the socket group (`DOCKER_GID` in Compose; detected socket GID for Linux `docker run`). Keep signed digest validation for updates dispatched by Central. Then follow `skills/compose-disposable-recipe/SKILL.md` with a unique project, generated credentials, isolated ports/volumes, and an EXIT cleanup trap installed before build/start. Never connect the recipe to a deployed Docker daemon or production data.
When a runtime Dockerfile changes for OS security updates, source-build and health-check the corresponding Central/Agent image, then scan its saved image archive with the pinned Trivy version and the same `HIGH,CRITICAL` severities used by CI. Record the finding IDs and fixed package versions; do not hide a nonzero scan behind application acceptance.
@@ -0,0 +1,22 @@
---
name: database-migration-startup
description: Diagnose and validate Heimdall Central's EF Core PostgreSQL migration startup, including first boot, restart, retry exhaustion, and recovery.
---
# Database migration startup
`src/Heimdall.Web/Program.cs` calls `Program.ApplyMigrationsAsync` before configuring recurring Hangfire jobs and seeding identity data. The method uses one `AppDbContext`, retries a failed `Database.MigrateAsync` five times with exponential delays, logs the terminal exception at Critical, then rethrows so Central cannot become ready with a failed migration.
For startup incidents, correlate the EF `CommandError` with the following `Program` retry/final logs. A failed EF command log alone does not prove that startup failed: a later retry may have succeeded. Preserve the provider exception and SQLSTATE when available, but never record a connection string, password, user identifier, or database row. Do not suppress EF command errors to hide a symptom.
## Acceptance
Run `bash skills/database-migration-startup/acceptance.sh` from a clean checkout. The recipe builds Central from this source with one unique local image tag, uses a fresh PostgreSQL database and generated credentials, and checks:
1. First boot applies migrations and `/healthz` becomes healthy.
2. A second startup against the migrated database remains healthy.
3. A synthetic database role with access to the database/schema but no `SELECT` on `public.__EFMigrationsHistory` causes migration startup to exhaust all five attempts, emit the final Critical failure, and exit nonzero without logging migration success.
4. Granting that role `SELECT` and restarting Central allows migration startup and health checks to succeed.
5. The EXIT trap removes only this Compose project and its exact image tag, then verifies that its containers, volumes, network, and image are absent. Shared PostgreSQL and .NET base images are retained.
This synthetic permission failure verifies fail-closed and recovery behavior; it does not establish the cause of a separate deployment's EF error. Record production evidence only when an event includes the provider exception/SQLSTATE and correlated startup outcome.
@@ -0,0 +1,198 @@
#!/usr/bin/env bash
set -Eeuo pipefail
project="heimdall-migration-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 4)"
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")"
env_file="$temp_dir/acceptance.env"
compose_override="$temp_dir/compose.override.yml"
failure_override="$temp_dir/compose.failure.yml"
recovery_override="$temp_dir/compose.recovery.yml"
compose_file="$(git rev-parse --show-toplevel)/docker/docker-compose.yml"
local_image_tags=("heimdall:${project}-central")
web_port="$(python3 - <<'PY'
import socket
s = socket.socket()
s.bind(('127.0.0.1', 0))
print(s.getsockname()[1])
s.close()
PY
)"
db_name="${project//-/_}"
db_user="migration_owner_${project//-/_}"
db_password="$(openssl rand -hex 24)"
probe_password="$(openssl rand -hex 24)"
jwt_key="$(openssl rand -base64 48 | tr -d '\n')"
jwt_refresh_key="$(openssl rand -base64 48 | tr -d '\n')"
cat > "$env_file" <<EOF
POSTGRES_DB=$db_name
POSTGRES_USER=$db_user
POSTGRES_PASSWORD=$db_password
DATABASE_URL=Host=postgresql;Port=5432;Database=$db_name;Username=$db_user;Password=$db_password
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$jwt_refresh_key
JWT__ISSUER=$project
JWT__AUDIENCE=$project
ASPNETCORE_ENVIRONMENT=Development
Sentry__Dsn=
SENTRY_DSN=
WEB_PORT=$web_port
HEIMDALL_NETWORK_NAME=${project}_net
ACCEPTANCE_PROJECT=$project
MIGRATION_PROBE_PASSWORD=$probe_password
EOF
chmod 600 "$env_file"
cat > "$compose_override" <<'EOF'
services:
postgresql:
ports: !override []
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
ports: !override
- "127.0.0.1:${WEB_PORT}:8080"
EOF
cat > "$failure_override" <<'EOF'
services:
heimdall:
environment:
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
restart: "no"
EOF
cat > "$recovery_override" <<'EOF'
services:
heimdall:
environment:
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
restart: "no"
EOF
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" down --volumes --remove-orphans || cleanup_failed=1
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
python3 - "$env_file" "$compose_override" "$failure_override" "$recovery_override" <<'PY' || cleanup_failed=1
import pathlib
import sys
for name in sys.argv[1:]:
pathlib.Path(name).unlink(missing_ok=True)
PY
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable migration recipe cleanup failed for project %s\n' "$project" >&2
status=1
else
printf 'Cleanup verified: project containers/volumes/network and exact tag absent (%s).\n' "${local_image_tags[*]}"
fi
exit "$status"
}
trap cleanup EXIT
for tag in "${local_image_tags[@]}"; do
if docker image inspect "$tag" >/dev/null 2>&1; then
printf 'Unique acceptance image tag already exists: %s\n' "$tag" >&2
exit 1
fi
done
compose() {
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" "$@"
}
compose config --quiet
compose up -d --build
base_url="http://127.0.0.1:$web_port"
wait_healthy() {
for attempt in $(seq 1 120); do
if curl --fail --silent "$base_url/healthz" -o /dev/null; then return 0; fi
sleep 2
done
return 1
}
wait_healthy || { echo 'Central did not become healthy after first migration.' >&2; exit 1; }
echo 'First boot: PostgreSQL fresh schema migrated; Central healthz returned HTTP 200.'
compose restart heimdall
wait_healthy || { echo 'Central did not recover against the migrated database.' >&2; exit 1; }
echo 'Restart: Central healthz returned HTTP 200 on the migrated schema.'
postgres_container="$(compose ps -q postgresql)"
[[ -n "$postgres_container" ]] || { echo 'PostgreSQL container was not found.' >&2; exit 1; }
docker exec -i "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
-v probe_password="$probe_password" <<'SQL'
CREATE ROLE migration_probe LOGIN PASSWORD :'probe_password';
SELECT format('GRANT CONNECT ON DATABASE %I TO migration_probe', current_database()) \gexec
GRANT USAGE ON SCHEMA public TO migration_probe;
GRANT CREATE ON SCHEMA public TO migration_probe;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO migration_probe;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO migration_probe;
GRANT USAGE, CREATE ON SCHEMA hangfire TO migration_probe;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA hangfire TO migration_probe;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA hangfire TO migration_probe;
REVOKE SELECT ON TABLE public."__EFMigrationsHistory" FROM migration_probe;
SQL
compose -f "$failure_override" up -d --force-recreate heimdall
web_container="$(compose -f "$failure_override" ps -q heimdall)"
[[ -n "$web_container" ]] || { echo 'Central failure-test container was not found.' >&2; exit 1; }
failure_state=""
for attempt in $(seq 1 90); do
failure_state="$(docker inspect -f '{{.State.Status}}' "$web_container" 2>/dev/null || true)"
[[ "$failure_state" == exited ]] && break
sleep 1
done
[[ "$failure_state" == exited ]] || { echo 'Central did not exit on a permanent migration permission failure.' >&2; exit 1; }
failure_exit_code="$(docker inspect -f '{{.State.ExitCode}}' "$web_container")"
[[ "$failure_exit_code" != 0 ]] || { echo 'Central exited successfully despite the permanent migration failure.' >&2; exit 1; }
failure_logs="$(docker logs "$web_container" 2>&1)"
application_logs="$(grep -E 'Applying database migrations \(attempt|Database migration attempt .* failed|Failed to apply database migrations after 5 attempts|Database migrations applied successfully|permission denied' <<<"$failure_logs" | grep -v 'HttpTransport: Envelope')"
attempt_count="$(grep -c 'Applying database migrations (attempt' <<<"$application_logs" || true)"
retry_count="$(grep -c 'Database migration attempt .* failed' <<<"$application_logs" || true)"
terminal_count="$(grep -c 'Failed to apply database migrations after 5 attempts' <<<"$application_logs" || true)"
success_count="$(grep -c 'Database migrations applied successfully' <<<"$application_logs" || true)"
[[ "$attempt_count" -eq 5 && "$retry_count" -eq 4 && "$terminal_count" -eq 1 && "$success_count" -eq 0 ]] || {
printf 'Retry log counts: attempts=%s retries=%s terminal=%s successes=%s\n' \
"$attempt_count" "$retry_count" "$terminal_count" "$success_count" >&2
grep -E 'Applying database migrations \(attempt|Database migration attempt|Failed to apply database migrations|Database migrations applied successfully' \
<<<"$application_logs" | cut -c1-240 >&2 || true
echo 'Permanent failure did not show five attempts, four retries, one terminal failure, and zero success logs.' >&2
exit 1
}
grep -qi 'permission denied' <<<"$application_logs" || {
echo 'The synthetic failure did not report the expected history-table permission denial.' >&2
exit 1
}
echo 'Permanent failure: permission denied on migration history; five attempts, four retries, final Critical error, nonzero exit, no migration-success log.'
docker exec "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
-c 'GRANT SELECT ON TABLE public."__EFMigrationsHistory" TO migration_probe;' >/dev/null
compose -f "$recovery_override" up -d --force-recreate heimdall
wait_healthy || {
echo 'Central did not recover after granting migration-history access.' >&2
docker logs "$(compose -f "$recovery_override" ps -q heimdall)" 2>&1 \
| grep -Ei 'failed|error|permission denied|database migration|migration.*success' \
| grep -v 'HttpTransport: Envelope' | cut -c1-240 | tail -n 20 >&2 || true
exit 1
}
echo 'Recovery: granting history-table SELECT allowed startup; Central healthz returned HTTP 200.'
+3 -3
View File
@@ -5,13 +5,13 @@ description: Keep installer-managed RustFS and coturn Compose services aligned w
# Installer-managed optional services
The Linux and Windows server installers run optional Compose files with the installation root as the current directory. They save service secrets in `optional/secrets/` and pass the root `.env` for interpolation. Therefore, Compose secret `file:` entries must use `./optional/secrets/<name>`, not `./secrets/<name>` or paths relative to `optional/`.
The Linux and Windows server installers save service secrets in `<install-root>/optional/secrets/`, backup scripts in `<install-root>/optional/scripts/`, and pass the root `.env` for interpolation. Compose resolves relative paths from its project directory, which otherwise defaults to the directory containing the first `-f` file. RustFS and coturn Compose files reference `./optional/secrets/<name>`, so start them with `--project-directory <install-root>`. The backup Compose references `./scripts` and `./secrets/db_password`, so start it with `--project-directory <install-root>/optional`. Preserve these service-specific bases; applying the installation root to every optional Compose breaks the backup mounts.
## RustFS
- Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers.
- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies).
- Verify Compose config from the install-root working directory and ensure Docker secrets are sourced from those files.
- Verify actual optional-service invocations use the right project directory: `<install-root>` for RustFS/coturn and `<install-root>/optional` for backup. Confirm normalized secret and script bind sources point to exact generated files/directories. A successful `config` without checking normalized source paths is insufficient because Compose can accept an unintended path that happens to exist.
- Keep the named data volume and shared `heimdall-net` behavior intact.
## coturn
@@ -26,4 +26,4 @@ The Linux and Windows server installers run optional Compose files with the inst
## Acceptance
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose using that root. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose with each installer's explicit project directory. It asserts the normalized RustFS/coturn secret paths and backup secret/script bind sources exactly match the generated files before starting containers. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images.
+43 -3
View File
@@ -7,13 +7,16 @@ project="heimdall-optional-services-${suffix}"
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
install_root="$temp_dir/install-root"
secret_dir="$install_root/optional/secrets"
backup_scripts_dir="$install_root/optional/scripts"
env_file="$temp_dir/acceptance.env"
override_file="$temp_dir/compose.override.yml"
turn_log="$temp_dir/turn-client.log"
rustfs_compose="$repo_root/docker/docker-compose.rustfs.yml"
coturn_compose="$repo_root/docker/docker-compose.coturn.yml"
backup_compose="$repo_root/docker/docker-compose.backup.yml"
backup_scripts=(backup.sh backup-protected-data.sh backup-rustfs.sh restore.sh restore-protected-data.sh)
local_image_tags=()
mkdir -p "$secret_dir"
mkdir -p "$secret_dir" "$backup_scripts_dir"
compose() {
docker compose --project-directory "$install_root" --env-file "$env_file" \
@@ -59,8 +62,11 @@ cleanup() {
done
rm -f -- "$env_file" "$override_file" "$turn_log" \
"$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \
"$secret_dir/coturn_secret" || cleanup_failed=1
rmdir -- "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1
"$secret_dir/coturn_secret" "$secret_dir/db_password" || cleanup_failed=1
for name in "${backup_scripts[@]}"; do
rm -f -- "$backup_scripts_dir/$name" || cleanup_failed=1
done
rmdir -- "$backup_scripts_dir" "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if ((cleanup_failed)); then
printf 'Disposable optional-service cleanup failed for %s\n' "$project" >&2
@@ -116,6 +122,10 @@ coturn_username=acceptance
printf '%s' "$rustfs_access_key" > "$secret_dir/rustfs_access_key"
printf '%s' "$rustfs_secret_key" > "$secret_dir/rustfs_secret_key"
printf '%s' "$coturn_secret" > "$secret_dir/coturn_secret"
printf 'acceptance-db-password-%s' "$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')" > "$secret_dir/db_password"
for name in "${backup_scripts[@]}"; do
cp "$repo_root/docker/scripts/$name" "$backup_scripts_dir/$name"
done
chmod 600 "$secret_dir"/*
cat > "$env_file" <<EOF
RUSTFS_API_PORT=$rustfs_api_port
@@ -129,6 +139,7 @@ COTURN_USERNAME=$coturn_username
RUSTFS_ACCESS_KEY=$rustfs_access_key
RUSTFS_SECRET_KEY=$rustfs_secret_key
ACCEPTANCE_NETWORK=${project}-heimdall-net
HEIMDALL_DATA_VOLUME=${project}-heimdall-data
EOF
chmod 600 "$env_file"
cat > "$override_file" <<'EOF'
@@ -155,6 +166,35 @@ EOF
printf 'Disposable project: %s\nLocal images built: none\n' "$project"
compose config --quiet
compose config --format json | INSTALL_ROOT="$install_root" python3 -c '
import json, os, sys
config = json.load(sys.stdin)
root = os.environ["INSTALL_ROOT"]
expected = {
"rustfs_access_key": os.path.join(root, "optional/secrets/rustfs_access_key"),
"rustfs_secret_key": os.path.join(root, "optional/secrets/rustfs_secret_key"),
"coturn_secret": os.path.join(root, "optional/secrets/coturn_secret"),
}
actual = {name: config["secrets"][name]["file"] for name in expected}
if actual != expected:
raise SystemExit("Compose secret bind mounts do not resolve under the installer root")
print("Verified RustFS and coturn secret bind mounts resolve under the installer root.")
'
docker compose --project-directory "$install_root/optional" --env-file "$env_file" \
-f "$backup_compose" --project-name "${project}-backup" config --format json |
BACKUP_PROJECT_DIRECTORY="$install_root/optional" python3 -c '
import json, os, sys
config = json.load(sys.stdin)
project_directory = os.environ["BACKUP_PROJECT_DIRECTORY"]
expected_secret = os.path.join(project_directory, "secrets/db_password")
expected_scripts = os.path.join(project_directory, "scripts")
actual_secret = config["secrets"]["db_password"]["file"]
scripts_mount = next((mount for mount in config["services"]["backup"]["volumes"]
if mount.get("target") == "/scripts"), None)
if actual_secret != expected_secret or scripts_mount is None or scripts_mount.get("source") != expected_scripts:
raise SystemExit("Backup secret or script bind mounts do not resolve under optional/")
print("Verified backup secret and scripts resolve under the installer optional directory.")
'
compose up -d rustfs coturn
base_url="http://127.0.0.1:$rustfs_api_port"
+1 -1
View File
@@ -27,7 +27,7 @@ Heimdall's connected Penpot file is part of the UI source of truth. Whenever a c
## Installer design reference
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, digest-pinned Docker image requirements, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
The installer should follow the interaction hierarchy represented by `site-agent-installer-ui/SKILL.md`: platform choices, platform-specific method choices, optional configuration, then titled command cards with deliberate copy controls. For the current Agent installer, keep the design aligned with supported Linux, Windows, and Docker options, release signing/update-key gates, Docker installation from the `latest` image tag, signed digest validation for updates dispatched by Central, and the actual command builders. Keep desktop and mobile layouts, plus release-unavailable states, represented. Update the existing installer frame and any relevant variations in the connected file on every behavior or layout change.
## Acceptance evidence
+3 -2
View File
@@ -7,10 +7,11 @@ description: Diagnose and maintain Renovate dependency updates through Gitea Act
Use this skill for `.gitea/workflows/renovate.yml`, `renovate.json`, or dependency-update failures.
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `GITEA_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files.
- The endpoint must be the HTTPS Gitea API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
- Renovate runs only on its weekly schedule or manual dispatch, on `[ubuntu-latest, build-agent]`, in the pinned Renovate container. Keep `RENOVATE_TOKEN` in Actions secrets and `FORGEJO_API_ENDPOINT` in Actions variables; do not add either credential or forge hostname to repository files. Forgejo reserves variable names beginning with `GITEA_` and rejects them.
- The endpoint must be the HTTPS Forgejo API root ending in `/api/v1`. The workflow checks that the token can call `/user` and read `arnaud.dartois/Heimdall` before Renovate starts. Preflight logs only response status and a safe diagnosis; never print request headers, response bodies, or token values.
- HTTP 401/403 means the secret is missing, expired, revoked, or lacks repository access. Configure a bot token with repository read and write access so Renovate can open pull requests. Read preflight success does not prove write access; confirm a successful run that opens or updates a PR.
- Use `node --test scripts/ci/renovate-preflight.test.mjs` to test endpoint validation and sanitized auth failures locally. Do not run Renovate locally with production credentials.
- Run `bash skills/renovate-automation/acceptance.sh` after changing the preflight or its endpoint wiring. It exercises valid and rejected synthetic credentials over an isolated HTTPS mock in Compose; the test container trusts only the generated self-signed certificate for its local fixture.
- For a changed preflight/deployment path, validate a disposable Compose project with a mock HTTPS API, a synthetic token, no host-published ports or persistent data, and both accepted and rejected credentials. Install an EXIT cleanup trap before startup, preserve the test exit status, remove that exact project, and confirm it leaves no containers, volumes, or networks; if pulling the Node base image is unavailable, record the blocker and rerun the recipe when registry access is restored.
- The mock-preflight recipe uses a shared upstream Node image and creates no local images. Retain that base image. If the recipe adds a locally built mock/helper/application image, record its unique tag and remove/verify only that exact tag in the same cleanup trap, including on failure. Do not use `--rmi all` or broad prune commands.
- For operational changes, update the Renovate Gitea issue with the workflow run and the remaining remote-secret validation. Never claim the bot works based only on configuration presence.
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
set -Eeuo pipefail
project="heimdall-renovate-acceptance-$(date -u +%Y%m%d%H%M%S)-$RANDOM"
repo_root=$(git rev-parse --show-toplevel)
temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")
compose_file="$temp_dir/compose.yml"
runner_file="$temp_dir/acceptance.mjs"
cert_file="$temp_dir/mock.crt"
key_file="$temp_dir/mock.key"
local_image_tags=()
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans || cleanup_failed=1
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
if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then cleanup_failed=1; fi
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" "$runner_file" "$cert_file" "$key_file" || cleanup_failed=1
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
echo "Disposable Compose cleanup failed for $project" >&2
status=1
else
echo "Verified no project containers, volumes, or networks; no local images built ($project)"
fi
exit "$status"
}
trap cleanup EXIT
openssl req -x509 -newkey rsa:2048 -nodes -keyout "$key_file" -out "$cert_file" \
-subj "/CN=localhost" -addext "subjectAltName=IP:127.0.0.1" -days 1 >/dev/null 2>&1
cat > "$runner_file" <<'NODE'
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createServer } from 'node:https';
import { checkGiteaAccess } from '/workspace/scripts/ci/renovate-preflight.mjs';
const requests = [];
const server = createServer({
key: readFileSync('/acceptance/mock.key'),
cert: readFileSync('/acceptance/mock.crt'),
}, (request, response) => {
requests.push({ path: request.url, authorization: request.headers.authorization });
if (request.headers.authorization !== 'token synthetic-valid') {
response.writeHead(401, { 'content-type': 'application/json' });
response.end('{"message":"credential rejected"}');
return;
}
response.writeHead(200, { 'content-type': 'application/json' });
response.end('{}');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
try {
const endpoint = `https://127.0.0.1:${server.address().port}/api/v1`;
await checkGiteaAccess(endpoint, 'synthetic-valid');
await assert.rejects(
checkGiteaAccess(endpoint, 'synthetic-invalid'),
error => error.message.includes('HTTP 401') &&
error.message.includes('RENOVATE_TOKEN') &&
!error.message.includes('synthetic-invalid') &&
!error.message.includes('credential rejected'),
);
assert.deepEqual(requests.map(({ path }) => path), [
'/api/v1/user', '/api/v1/repos/arnaud.dartois/Heimdall',
'/api/v1/user',
]);
assert.ok(requests.every(({ authorization }) =>
['token synthetic-valid', 'token synthetic-invalid'].includes(authorization)));
console.log('HTTPS mock preflight accepted valid and rejected invalid synthetic credentials without exposing response details.');
} finally {
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
}
NODE
cat > "$compose_file" <<EOF
services:
acceptance:
image: node:22-alpine
working_dir: /workspace
volumes:
- "$repo_root:/workspace:ro"
- "$temp_dir:/acceptance:ro"
environment:
NODE_EXTRA_CA_CERTS: /acceptance/mock.crt
command: ["node", "/acceptance/acceptance.mjs"]
EOF
docker compose -p "$project" -f "$compose_file" config --quiet
docker compose -p "$project" -f "$compose_file" run --rm acceptance
+31
View File
@@ -0,0 +1,31 @@
---
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.
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.
+1 -1
View File
@@ -11,7 +11,7 @@ Keep the site Agent installer in `src/Heimdall.Web/Components/SiteInstallPanel.r
- Offer only Heimdall-supported platforms: Linux, Windows, and Docker. Keep method choices mapped in `AvailableMethods` and reset to that platform's sensible default in `SelectOperatingSystem`.
- Keep generated command content in the existing builders and `Commands` projection. Platform selection controls the builders; do not duplicate generated commands in markup.
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require a digest-pinned image reference and update key. Preserve these gates so the panel never offers a nonfunctional installer.
- Native install commands require a latest signed release with update key, signed manifest, signature, and Agent archive assets. Docker commands additionally require verified CPU/GPU image metadata and the update key, but install the corresponding published `:latest` image. Generated Compose uses `pull_policy: always`; generated Docker Run commands use `--pull always`. Preserve signed digest validation for Agent updates dispatched later by Central.
- Treat site tokens and generated configuration as secrets: show them only in the authenticated site's installer view and copy only after a deliberate click. Do not log generated content.
- For live installer verification, use the authenticated Orca browser session. Check for the dedicated Heimdall login only in the user secret store at `~/.config/heimdall/credentials.json`; never put account passwords in this skill, repository config, shell arguments, or Orca `fill` commands. The file fallback is owner-only (`0700` directory, `0600` file) and base64-encoded, not encrypted. If it is absent, provide the user-run masked helper `~/.local/bin/store-heimdall-credentials`; do not report the credentials as persisted until that helper succeeds. If Orca has no safe autofill path, ask the user to enter the password in the visible browser.
- Keep all visible strings in `SharedResources.resx`, `SharedResources.en.resx`, and `SharedResources.fr.resx`.
+42 -1
View File
@@ -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,28 @@ 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`.
- 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
View File
@@ -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);
}
@@ -53,6 +53,7 @@ public sealed class SnapshotPipelineService : BackgroundService
private readonly FrameResizer? _resizer;
private readonly ILogger<SnapshotPipelineService> _logger;
private readonly SemaphoreSlim _syncLock = new(1, 1);
private readonly SemaphoreSlim _configChanged = new(0, 1);
private readonly Dictionary<Guid, string> _streamUrls = new();
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
private readonly ConcurrentDictionary<Guid, SceneState> _reportedSceneState = new();
@@ -154,8 +155,18 @@ public sealed class SnapshotPipelineService : BackgroundService
// (e.g. camera settings applied before we subscribed).
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || DateTime.UtcNow.Second % 30 == 0)
var periodicSyncDue = false;
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken))
{
wait.CancelAfter(TimeSpan.FromSeconds(1));
try { await _configChanged.WaitAsync(wait.Token); }
catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested)
{
periodicSyncDue = true;
}
}
if (Interlocked.Exchange(ref _configDirty, 0) != 0 || periodicSyncDue && DateTime.UtcNow.Second % 30 == 0)
await SyncStreamsAsync(stoppingToken);
}
}
@@ -181,6 +192,8 @@ public sealed class SnapshotPipelineService : BackgroundService
private void OnCameraConfigChanged(object? sender, EventArgs e)
{
Interlocked.Exchange(ref _configDirty, 1);
try { _configChanged.Release(); }
catch (SemaphoreFullException) { }
}
private async Task SyncStreamsAsync(CancellationToken ct)
@@ -246,15 +246,15 @@ else if (_method == "windows-service")
release?.Assets.Count > 0;
if (!string.IsNullOrWhiteSpace(release?.ContainerImage) &&
!string.IsNullOrWhiteSpace(release.ContainerImageDigest))
_agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}";
_agentImageReference = LatestImageReference(release.ContainerImage);
if (!string.IsNullOrWhiteSpace(release?.ContainerImageGpu) &&
!string.IsNullOrWhiteSpace(release.ContainerImageGpuDigest))
_agentGpuImageReference = $"{release.ContainerImageGpu}@{release.ContainerImageGpuDigest}";
_agentGpuImageReference = LatestImageReference(release.ContainerImageGpu);
_updatePublicKeyPem = release?.UpdatePublicKeyPem;
}
catch
{
// Native installers fetch signed release metadata directly; Docker needs a verified image reference and key.
// Native installers fetch signed release metadata directly; Docker needs verified image metadata and key.
}
finally
{
@@ -262,6 +262,14 @@ else if (_method == "windows-service")
}
}
private static string LatestImageReference(string image)
{
var lastSlash = image.LastIndexOf('/');
var lastColon = image.LastIndexOf(':');
var repository = lastColon > lastSlash ? image[..lastColon] : image;
return $"{repository}:latest";
}
private string ComposeYaml
{
get
@@ -277,6 +285,7 @@ else if (_method == "windows-service")
services:
heimdall-agent:
image: {{image}}
pull_policy: always
container_name: heimdall-agent-{{safeName}}
restart: unless-stopped
user: "1654:1654"
@@ -307,6 +316,7 @@ else if (_method == "windows-service")
agent-state-init:
image: {{image}}
pull_policy: always
user: "0:0"
entrypoint: ["chown", "-R", "1654:1654", "/state"]
volumes:
@@ -337,7 +347,7 @@ else if (_method == "windows-service")
var name = "heimdall-agent-" + Slugify(SiteName);
var volume = "heimdall-agent-state-" + Slugify(SiteName);
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
return $"docker run --pull always -d --name {name} --restart unless-stopped --network host --user 1654:1654 " +
(_useGpuImage ? "--gpus all " : "") +
"--group-add \"$(stat -c '%g' /var/run/docker.sock)\" " +
"-v /var/run/docker.sock:/var/run/docker.sock " +
@@ -370,7 +380,7 @@ else if (_method == "windows-service")
var name = "heimdall-agent-" + Slugify(SiteName);
var volume = "heimdall-agent-state-" + Slugify(SiteName);
var image = _useGpuImage ? _agentGpuImageReference : _agentImageReference;
var args = new List<string> { "run", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
var args = new List<string> { "run", "--pull", "always", "-d", "--name", name, "--restart", "unless-stopped", "--user", "1654:1654", "--publish", "127.0.0.1:8081:8080", "--group-add", "0", "-v", "/var/run/docker.sock:/var/run/docker.sock" };
if (_useGpuImage) args.AddRange(["--gpus", "all"]);
args.AddRange([
"-e", "Agent__CentralUrl=" + CentralUrl,
@@ -4078,7 +4078,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<value>Docker installation uses the latest image. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
@@ -4078,7 +4078,7 @@
<value>Vérifier</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<value>L’installation Docker utilise l’image latest. Les mises à jour déclenchées par Central vérifient le digest signé avant de remplacer l’Agent. Le mode Docker monte le socket Docker de l’hôte, ce qui donne à l’Agent un contrôle étendu sur cet hôte. Sous Linux, avant Compose, définissez DOCKER_GID avec le GID du socket : export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>L’Agent démarre en arrière-plan pour permettre la vérification depuis cette console. Le mode Service Windows le relance après fermeture de session ou redémarrage.</value>
@@ -4078,7 +4078,7 @@
<value>Check</value>
</data>
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
<value>Container updates use Docker or Kubernetes. Heimdall pins each image to its signed digest. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
<value>Docker installation uses the latest image. Updates dispatched by Central verify the signed digest before replacing the Agent. Docker mode mounts the host Docker socket, giving the Agent broad control of that host. On Linux, before Compose, set DOCKER_GID to the socket GID: export DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)".</value>
</data>
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
<value>The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot.</value>
@@ -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)
@@ -9,7 +9,7 @@ public class SnapshotPipelineServiceTests
{
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline(
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer, ICameraStatusReporter StatusReporter) CreatePipeline(
List<AgentCameraOptions>? cameras = null,
AnalysisMode analysisMode = AnalysisMode.Local,
string? brokerUrl = null)
@@ -34,13 +34,13 @@ public class SnapshotPipelineServiceTests
state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter,
Substitute.For<ILogger<SnapshotPipelineService>>(),
DegradationManager: degradationManager, Metrics: metrics));
return (service, state, store, streams, analyzer);
return (service, state, store, streams, analyzer, statusReporter);
}
[Fact]
public async Task StartStop_WithoutRegistration_StopsGracefully()
{
var (service, state, _, _, _) = CreatePipeline();
var (service, state, _, _, _, _) = CreatePipeline();
state.AgentId = Guid.Empty; // never registered
await service.StartAsync(CancellationToken.None);
@@ -52,7 +52,7 @@ public class SnapshotPipelineServiceTests
[Fact]
public async Task StartStop_WithNoCameras_DoesNotStartStreams()
{
var (service, _, _, streams, _) = CreatePipeline();
var (service, _, _, streams, _, _) = CreatePipeline();
await service.StartAsync(CancellationToken.None);
try
{
@@ -72,7 +72,7 @@ public class SnapshotPipelineServiceTests
{
new() { Name = "Cam 1", RtspUrl = "rtsp://cam1/stream" },
};
var (service, _, store, streams, _) = CreatePipeline(cameras);
var (service, _, store, streams, _, _) = CreatePipeline(cameras);
await service.StartAsync(CancellationToken.None);
try
@@ -93,10 +93,45 @@ public class SnapshotPipelineServiceTests
}
}
[Fact]
public async Task CameraConfigChanged_ReconcilesWithoutWaitingForPeriodicSync()
{
var (service, _, store, streams, _, statusReporter) = CreatePipeline();
var cameraId = Guid.NewGuid();
await service.StartAsync(CancellationToken.None);
try
{
await Task.Delay(TimeSpan.FromMilliseconds(1100));
statusReporter.ClearReceivedCalls();
store.ReplaceCentral(new Dictionary<string, string>
{
[$"camera.{cameraId}.enabled"] = "true",
[$"camera.{cameraId}.rtsp"] = "rtsp://camera/test",
});
// The full periodic resync runs every 30 seconds. A config event
// must instead reconcile this transition on the event signal.
var deadline = DateTime.UtcNow.AddMilliseconds(500);
while (DateTime.UtcNow < deadline && !statusReporter.ReceivedCalls().Any())
await Task.Delay(10);
streams.ActiveStreamCount.ShouldBe(0); // FFmpeg is intentionally absent.
// Error is reported only after the enabled assignment is reconciled.
statusReporter.ReceivedCalls().Any(call =>
call.GetMethodInfo().Name == nameof(ICameraStatusReporter.ReportAsync) &&
Equals(call.GetArguments()[0], cameraId) &&
Equals(call.GetArguments()[1], "Error")).ShouldBeTrue();
}
finally
{
await service.StopAsync(CancellationToken.None);
}
}
[Fact]
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
{
var (service, _, store, streams, analyzer) = CreatePipeline();
var (service, _, store, streams, analyzer, _) = CreatePipeline();
var id = Guid.NewGuid();
store.ReplaceCentral(new Dictionary<string, string>
{
@@ -128,7 +163,7 @@ public class SnapshotPipelineServiceTests
[Fact]
public async Task StopAsync_WithoutStart_DoesNotThrow()
{
var (service, _, _, _, _) = CreatePipeline();
var (service, _, _, _, _, _) = CreatePipeline();
await service.StopAsync(CancellationToken.None);
service.ShouldNotBeNull();
}
@@ -136,7 +171,7 @@ public class SnapshotPipelineServiceTests
[Fact]
public void IsRemoteMode_LocalMode_ReturnsFalse()
{
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
service.IsRemoteMode.ShouldBeFalse();
}
@@ -144,14 +179,14 @@ public class SnapshotPipelineServiceTests
public void IsRemoteMode_RemoteMode_NoBroker_ReturnsFalse()
{
// Remote mode but no broker service injected → not actually remote
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
var (service, _, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
service.IsRemoteMode.ShouldBeFalse();
}
[Fact]
public void RemoteSubmissions_InitiallyZero()
{
var (service, _, _, _, _) = CreatePipeline();
var (service, _, _, _, _, _) = CreatePipeline();
service.RemoteSubmissions.ShouldBe(0);
service.RemoteFallbacks.ShouldBe(0);
}
@@ -82,7 +82,8 @@ public class SiteDetailTests : PageTestBase
cut.Markup.ShouldContain("Agent__SiteToken");
cut.Markup.ShouldContain("Régénérer");
var compose = cut.Find("pre code").TextContent;
compose.ShouldContain("registry.example/heimdall-agent@sha256:");
compose.ShouldContain("image: registry.example/heimdall-agent:latest");
compose.ShouldContain("pull_policy: always");
compose.ShouldContain("network_mode: host");
compose.ShouldContain("Agent__CentralUrl: \"http://localhost\"");
compose.ShouldContain("Agent__SiteToken: \"tok-detail-42\"");
@@ -93,9 +94,31 @@ public class SiteDetailTests : PageTestBase
compose.ShouldNotContain("ollama");
var agent = GetAgentService(ParseCompose(compose));
agent.Children.ShouldNotContainKey(new YamlScalarNode("deploy"));
((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value
.ShouldBe("registry.example/heimdall-agent:latest");
((YamlScalarNode)agent.Children[new YamlScalarNode("pull_policy")]).Value.ShouldBe("always");
var volumes = (YamlSequenceNode)agent.Children[new YamlScalarNode("volumes")];
volumes.Children.Select(node => ((YamlScalarNode)node).Value)
.ShouldContain("/var/run/docker.sock:/var/run/docker.sock");
var groups = (YamlSequenceNode)agent.Children[new YamlScalarNode("group_add")];
groups.Children.Select(node => ((YamlScalarNode)node).Value)
.ShouldContain("${DOCKER_GID:-0}");
var environment = (YamlMappingNode)agent.Children[new YamlScalarNode("environment")];
((YamlScalarNode)environment.Children[new YamlScalarNode("Agent__InferenceExecutionProvider")]).Value.ShouldBe("CPU");
});
cut.FindAll("button").Single(b => b.TextContent.Contains("Docker Run", StringComparison.OrdinalIgnoreCase)).Click();
cut.WaitForAssertion(() =>
{
var commands = cut.FindAll("pre code").Select(code => code.TextContent).ToArray();
commands.Length.ShouldBe(6);
commands[0].ShouldContain("docker pull registry.example/heimdall-agent:latest");
commands[1].ShouldContain("--pull always");
commands[1].ShouldContain("registry.example/heimdall-agent:latest");
commands[3].ShouldContain("docker pull 'registry.example/heimdall-agent:latest'");
commands[4].ShouldContain("'--pull','always'");
commands[4].ShouldContain("'registry.example/heimdall-agent:latest'");
});
}
[Fact]
@@ -137,14 +160,16 @@ public class SiteDetailTests : PageTestBase
cut.WaitForAssertion(() =>
{
var compose = cut.Find("pre code").TextContent;
compose.ShouldContain("image: registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
compose.ShouldContain("image: registry.example/heimdall-agent-gpu:latest");
compose.ShouldContain("pull_policy: always");
compose.ShouldContain("Agent__InferenceExecutionProvider: CUDA");
compose.ShouldContain("driver: nvidia");
compose.ShouldContain("capabilities: [gpu]");
compose.ShouldContain("\n deploy:\n resources:\n reservations:");
var agent = GetAgentService(ParseCompose(compose));
((YamlScalarNode)agent.Children[new YamlScalarNode("image")]).Value.ShouldBe(
"registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
"registry.example/heimdall-agent-gpu:latest");
((YamlScalarNode)agent.Children[new YamlScalarNode("pull_policy")]).Value.ShouldBe("always");
var deploy = (YamlMappingNode)agent.Children[new YamlScalarNode("deploy")];
var resources = (YamlMappingNode)deploy.Children[new YamlScalarNode("resources")];
var reservations = (YamlMappingNode)resources.Children[new YamlScalarNode("reservations")];
@@ -159,7 +184,12 @@ public class SiteDetailTests : PageTestBase
var run = commands[1];
run.ShouldContain("--gpus all");
run.ShouldContain("Agent__InferenceExecutionProvider=CUDA");
run.ShouldContain("registry.example/heimdall-agent-gpu@sha256:" + new string('b', 64));
run.ShouldContain("--pull always");
run.ShouldContain("registry.example/heimdall-agent-gpu:latest");
run.ShouldContain("--group-add \"$(stat -c '%g' /var/run/docker.sock)\"");
run.ShouldContain("-v /var/run/docker.sock:/var/run/docker.sock");
commands[4].ShouldContain("'--pull','always'");
commands[4].ShouldContain("'registry.example/heimdall-agent-gpu:latest'");
});
}