Alarik is a drop-in S3-compatible replacement requiring no application code changes. All S3 APIs (upload, download, list, delete, multipart) are fully supported.
451 lines
14 KiB
Markdown
451 lines
14 KiB
Markdown
# Heimdall — SignalR : Tous les hubs, events temps réel
|
|
|
|
**Stack :** SignalR (intégré à ASP.NET Core) — pas de lib externe supplémentaire
|
|
|
|
---
|
|
|
|
## 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 |
|
|
|---|---|---|---|
|
|
| `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 |
|
|
|
|
### Exemple d'envoi
|
|
|
|
```csharp
|
|
// Dans le handler de détection IA
|
|
public class DetectionResultHandler
|
|
{
|
|
private readonly IHubContext<EventsHub> _hub;
|
|
|
|
public async Task HandleAsync(DetectionResult result, CancellationToken ct)
|
|
{
|
|
var dto = _mapper.Map<EventDto>(result);
|
|
|
|
// Envoyer au groupe du site
|
|
await _hub.Clients
|
|
.Group($"site-{result.SiteId}")
|
|
.SendAsync("EventCreated", dto, ct);
|
|
|
|
// 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 |
|
|
|---|---|---|---|
|
|
| **Agent** (SIPSorcery) | `RegisterSource` | SendSdp, SendIceCandidate | ViewerConnected, ViewerDisconnected, SdpAnswer, IceCandidate |
|
|
| **Browser** (Blazor) | `RequestStream` | SendAnswer, SendIceCandidate, StopStreaming | SdpOffer, IceCandidate |
|
|
|
|
---
|
|
|
|
## 4. Hub /hubs/monitoring — Status temps réel
|
|
|
|
```csharp
|
|
[Authorize]
|
|
public class MonitoringHub : Hub
|
|
{
|
|
public override async Task OnConnectedAsync()
|
|
{
|
|
var userId = Context.User.GetUserId();
|
|
var isAdmin = Context.User.IsInRole(AppRoles.Admin);
|
|
|
|
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();
|
|
|
|
foreach (var siteId in siteIds)
|
|
await Groups.AddToGroupAsync(
|
|
Context.ConnectionId, $"monitoring-site-{siteId}");
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
### Événements émis
|
|
|
|
| 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 Alarik mis à jour |
|
|
| `GpuUsageUpdated` | `GpuDto` | Admin | Utilisation GPU CodeProject.AI |
|
|
| `JobStatusChanged` | `JobDto` | Admin | Un job Hangfire échoue |
|
|
| `SystemHealthChanged` | `HealthDto` | Admin | Health check global |
|
|
|
|
### Exemple — Agent offline détecté
|
|
|
|
```csharp
|
|
// Déclenché par le heartbeat timeout
|
|
BackgroundJob.Schedule<AgentTimeoutJob>(
|
|
j => j.ExecuteAsync(agentId, CancellationToken.None),
|
|
TimeSpan.FromSeconds(90));
|
|
|
|
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;
|
|
|
|
if (agent.LastHeartbeat < DateTime.UtcNow.AddSeconds(-90))
|
|
{
|
|
agent.Status = AgentStatus.Offline;
|
|
await _db.SaveChangesAsync(ct);
|
|
|
|
// 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);
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 5. Hub /hubs/notifications — Notifications in-app
|
|
|
|
```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}");
|
|
}
|
|
|
|
/// <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));
|
|
}
|
|
|
|
/// <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));
|
|
|
|
// Mettre à jour le badge
|
|
await Clients.Caller.SendAsync("UnreadCount", 0);
|
|
}
|
|
}
|
|
```
|
|
|
|
### Événements émis
|
|
|
|
| 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 |
|
|
|
|
---
|
|
|
|
## 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
|
|
``` |