3 Commits
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
8 changed files with 629 additions and 508 deletions

No files matched your search

+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)
```
+26 -30
View File
@@ -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
+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.
+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);
}
@@ -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)