feat(events): add SignalR real-time event broadcasting to web UI

This commit is contained in:
Arnaud Dartois committed 2026-07-19 15:24:52 +00:00
1 parent 0d2f0574c9
commit c5728fa810
5 files changed
+121 -9

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Heimdall.Api.Hubs;
/// <summary>
/// SignalR hub for real-time camera events pushed to the web UI.
/// Connected clients receive new events instantly (motion, person, vehicle, etc.)
/// without polling.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class EventsHub : Hub
{
private readonly ILogger<EventsHub> _logger;
public EventsHub(ILogger<EventsHub> logger) => _logger = logger;
/// <summary>
/// Clients call this to join a group-filtered event feed (e.g., per site).
/// </summary>
public async Task JoinSiteEvents(string siteId)
{
if (!Guid.TryParse(siteId, out _))
{
await Clients.Caller.SendAsync("Error", "Invalid siteId format");
return;
}
await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}");
_logger.LogDebug("Client {ConnectionId} joined site events group {SiteId}", Context.ConnectionId, siteId);
}
/// <summary>
/// Clients call this to leave a group-filtered event feed.
/// </summary>
public async Task LeaveSiteEvents(string siteId)
{
if (!Guid.TryParse(siteId, out _)) return;
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}");
}
public override async Task OnConnectedAsync()
{
_logger.LogDebug("Client connected to events hub: {ConnectionId}", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
_logger.LogDebug("Client disconnected from events hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
}
/// <summary>
/// Sends SignalR notifications when new camera events are created.
/// Uses IHubContext for thread-safe broadcasting outside of hub connections.
/// </summary>
public class EventBroadcastService : IEventBroadcastService
{
private readonly IHubContext<EventsHub> _hubContext;
private readonly ILogger<EventBroadcastService> _logger;
public EventBroadcastService(IHubContext<EventsHub> hubContext, ILogger<EventBroadcastService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
public async Task NotifyEventCreated(CameraEventResponse ev, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting new event: {EventId} type={Type} camera={CameraId}", ev.Id, ev.Type, ev.CameraId);
await _hubContext.Clients.All.SendAsync("EventCreated", ev, ct);
}
}
+3
View File
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.RateLimiting;
using Scalar.AspNetCore;
using Heimdall.Api.Filters;
using Heimdall.Application;
using Heimdall.Application.Services;
using Heimdall.Infrastructure;
using Heimdall.Api.Hubs;
using Heimdall.Infrastructure.Data;
@@ -61,6 +62,7 @@ else
}
builder.Services.AddSignalR();
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
builder.Services.AddOpenApi();
@@ -261,5 +263,6 @@ app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ConfigHub>("/hubs/config");
app.MapHub<EventsHub>("/hubs/events");
app.Run();
@@ -0,0 +1,13 @@
using Heimdall.Application.DTOs;
namespace Heimdall.Application.Services;
/// <summary>
/// Broadcasts camera events to connected clients (SignalR / WebSocket).
/// Implemented in the API layer; referenced by Infrastructure for decoupled
/// notification after event creation.
/// </summary>
public interface IEventBroadcastService
{
Task NotifyEventCreated(CameraEventResponse ev, CancellationToken ct = default);
}
@@ -4,6 +4,7 @@ using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
@@ -11,13 +12,16 @@ namespace Heimdall.Infrastructure.Services;
public sealed class CameraEventService : ICameraEventService
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<CameraEventService> _logger;
public CameraEventService(
IDbContextFactory<AppDbContext> dbFactory,
IServiceProvider serviceProvider,
ILogger<CameraEventService> logger)
{
_dbFactory = dbFactory;
_serviceProvider = serviceProvider;
_logger = logger;
}
@@ -40,6 +44,21 @@ public sealed class CameraEventService : ICameraEventService
"Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}",
ev.Id, ev.Type, ev.Confidence, ev.CameraId);
// Fire-and-forget broadcast to connected SignalR clients
_ = Task.Run(async () =>
{
try
{
using var scope = _serviceProvider.CreateScope();
var broadcast = scope.ServiceProvider.GetRequiredService<IEventBroadcastService>();
await broadcast.NotifyEventCreated(MapResponse(ev));
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to broadcast event {EventId}", ev.Id);
}
}, CancellationToken.None);
return ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
}
@@ -15,6 +15,7 @@ public class CameraEventServiceTests
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<CameraEventService> _logger = Substitute.For<ILogger<CameraEventService>>();
private readonly IServiceProvider _serviceProvider = Substitute.For<IServiceProvider>();
public CameraEventServiceTests()
{
@@ -47,7 +48,7 @@ public class CameraEventServiceTests
[Fact]
public async Task CreateAsync_ValidRequest_ReturnsEvent()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var result = await service.CreateAsync(new CreateCameraEventRequest(
@@ -63,7 +64,7 @@ public class CameraEventServiceTests
[Fact]
public async Task CreateAsync_UnknownCamera_ReturnsNotFound()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var result = await service.CreateAsync(new CreateCameraEventRequest(
Guid.NewGuid(), EventType.MotionDetected, 0.9, null, null, null),
CancellationToken.None);
@@ -75,7 +76,7 @@ public class CameraEventServiceTests
[Fact]
public async Task GetByIdAsync_ExistingId_ReturnsEvent()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var created = await service.CreateAsync(new CreateCameraEventRequest(
@@ -90,7 +91,7 @@ public class CameraEventServiceTests
[Fact]
public async Task GetByIdAsync_UnknownId_ReturnsNotFound()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var result = await service.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
@@ -99,7 +100,7 @@ public class CameraEventServiceTests
[Fact]
public async Task QueryAsync_FilterByType_ReturnsFiltered()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.9, null, null, null), CancellationToken.None);
@@ -118,7 +119,7 @@ public class CameraEventServiceTests
[Fact]
public async Task QueryAsync_FilterByMinConfidence_ReturnsFiltered()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.95, null, null, null), CancellationToken.None);
@@ -135,7 +136,7 @@ public class CameraEventServiceTests
[Fact]
public async Task DeleteAsync_ExistingEvent_RemovesIt()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var created = await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.9, null, null, null), CancellationToken.None);
@@ -150,7 +151,7 @@ public class CameraEventServiceTests
[Fact]
public async Task AttachSnapshotAsync_ExistingEvent_UpdatesSnapshot()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
var created = await service.CreateAsync(new(cameraId, EventType.MotionDetected, 0.9, null, null, null), CancellationToken.None);
@@ -171,7 +172,7 @@ public class CameraEventServiceTests
[Fact]
public async Task GetRecentByCameraAsync_ReturnsLatest()
{
var service = new CameraEventService(_dbFactory, _logger);
var service = new CameraEventService(_dbFactory, _serviceProvider, _logger);
var (_, cameraId) = await SeedCameraAsync();
for (int i = 0; i < 5; i++)