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>
This commit was merged in pull request #352.
This commit is contained in:
arnaud.dartois authored and Arnaud Dartois committed 2026-11-13 00:22:07 +01:00
1 parent 3ef030086d
commit 72edf1c514
3 files changed
+117 -428

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)
+10 -8
View File
@@ -131,25 +131,27 @@ 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 — cible non livrée
- 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 streaming WebRTC reste une cible non implémentée : l’application ne mappe pas
de hub `/hubs/streaming` et ne fournit pas de signaling SDP/ICE. Voir
[`docs/signalr-usage.md`](signalr-usage.md) pour les routes SignalR effectivement livrées.
## 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`
+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.