Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Failing after 2m11s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 3s
177 lines
8.6 KiB
C#
177 lines
8.6 KiB
C#
using Heimdall.Api.Security;
|
|
using Heimdall.Application.Common;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Heimdall.Application.Metrics;
|
|
using Heimdall.Application.Services;
|
|
|
|
namespace Heimdall.Api.Hubs;
|
|
|
|
/// <summary>
|
|
/// SignalR hub for real-time configuration push to agents.
|
|
/// Agents connect and receive config updates instantly when settings change.
|
|
/// </summary>
|
|
[Authorize(AuthenticationSchemes = "ApiKey")]
|
|
public class ConfigHub : Hub
|
|
{
|
|
private readonly ILogger<ConfigHub> _logger;
|
|
private readonly LiveSubscriptions _subscriptions;
|
|
private readonly ResourceAccess _access;
|
|
|
|
public ConfigHub(ILogger<ConfigHub> logger, ResourceAccess access, LiveSubscriptions subscriptions)
|
|
{
|
|
_logger = logger;
|
|
_access = access;
|
|
_subscriptions = subscriptions;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Agents call this on connect to join their personal config channel.
|
|
/// The agentId comes from the authenticated API key's associated agent.
|
|
/// </summary>
|
|
public async Task JoinAgentGroup(string agentId)
|
|
{
|
|
if (!Guid.TryParse(agentId, out var agent)) throw new HubException("Access denied");
|
|
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
|
|
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
|
!await _access.AgentAsync(requester, agent, Context.ConnectionAborted))
|
|
throw new HubException("Access denied");
|
|
_subscriptions.Join("config", Context.ConnectionId, $"agent_{agent}", Context.User!);
|
|
await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agent}");
|
|
}
|
|
|
|
public override async Task OnConnectedAsync()
|
|
{
|
|
var requester = await _access.ResolveAsync(Context.User, Context.ConnectionAborted);
|
|
if (requester is null || requester.Kind != RequesterKind.Agent) throw new HubException("Access denied");
|
|
_subscriptions.Join("config", Context.ConnectionId, "all", Context.User!);
|
|
HeimdallMetrics.SignalRConnectionAdded("config");
|
|
_logger.LogInformation("Agent connected to config hub: {ConnectionId}", Context.ConnectionId);
|
|
await base.OnConnectedAsync();
|
|
}
|
|
|
|
public override async Task OnDisconnectedAsync(Exception? exception)
|
|
{
|
|
_subscriptions.Disconnect("config", Context.ConnectionId);
|
|
HeimdallMetrics.SignalRConnectionRemoved("config");
|
|
_logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId);
|
|
await base.OnDisconnectedAsync(exception);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Broadcasts config changes to connected agents via SignalR.
|
|
/// Database-backed access services are resolved in a short-lived scope when a
|
|
/// notification is sent. AppDbContext invokes this service after saves, so
|
|
/// resolving those services in the constructor would create a DI cycle.
|
|
/// </summary>
|
|
public class ConfigBroadcastService : IConfigBroadcastService
|
|
{
|
|
private readonly IHubContext<ConfigHub> _hubContext;
|
|
private readonly ILogger<ConfigBroadcastService> _logger;
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
|
|
public ConfigBroadcastService(
|
|
IHubContext<ConfigHub> hubContext,
|
|
ILogger<ConfigBroadcastService> logger,
|
|
IServiceScopeFactory scopeFactory)
|
|
{
|
|
_hubContext = hubContext;
|
|
_logger = logger;
|
|
_scopeFactory = scopeFactory;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var services = scope.ServiceProvider;
|
|
var db = services.GetRequiredService<IApplicationDbContext>();
|
|
if (!await db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return;
|
|
_logger.LogDebug("Broadcasting global setting change: {Key}", key);
|
|
var access = services.GetRequiredService<ResourceAccess>();
|
|
var subscriptions = services.GetRequiredService<LiveSubscriptions>();
|
|
if (string.Equals(key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await _hubContext.Clients.Clients(await subscriptions.AuthorizedAsync("config", "all", access,
|
|
r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("ConfigReload", ct);
|
|
return;
|
|
}
|
|
await _hubContext.Clients.Clients(await subscriptions.AuthorizedAsync("config", "all", access, r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("SettingChanged", key, value, ct);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var services = scope.ServiceProvider;
|
|
var access = services.GetRequiredService<ResourceAccess>();
|
|
var subscriptions = services.GetRequiredService<LiveSubscriptions>();
|
|
|
|
// Keep the existing internal producer contract, but send commands as a
|
|
// separate, valueless event. SettingChanged always requires AgentScoped.
|
|
if (key == "discovery.scan.requested" && value == "1")
|
|
{
|
|
var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access,
|
|
r => access.AgentAsync(r, agentId, ct), ct);
|
|
await _hubContext.Clients.Clients(recipients).SendAsync("DiscoveryScanRequested", ct);
|
|
return;
|
|
}
|
|
var db = services.GetRequiredService<IApplicationDbContext>();
|
|
if (!await db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return;
|
|
_logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key}", agentId, key);
|
|
var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access,
|
|
r => access.AgentAsync(r, agentId, ct), ct);
|
|
if (string.Equals(key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await _hubContext.Clients.Clients(recipients).SendAsync("ConfigReload", ct);
|
|
return;
|
|
}
|
|
await _hubContext.Clients.Clients(recipients).SendAsync("SettingChanged", key, value, ct);
|
|
}
|
|
|
|
/// <summary>Requests an immediate update check from connected, authorized agents.</summary>
|
|
public async Task<bool> RequestAgentUpdate(Guid agentId, CancellationToken ct = default)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var services = scope.ServiceProvider;
|
|
var access = services.GetRequiredService<ResourceAccess>();
|
|
var subscriptions = services.GetRequiredService<LiveSubscriptions>();
|
|
var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access,
|
|
r => access.AgentAsync(r, agentId, ct), ct);
|
|
if (recipients.Count == 0) return false;
|
|
await _hubContext.Clients.Clients(recipients).SendAsync("AgentUpdateRequested", ct);
|
|
_logger.LogInformation("Requested update check from agent {AgentId}", agentId);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>Requests one frame from the assigned agent's active camera stream.</summary>
|
|
public async Task<bool> RequestManualSnapshot(Guid agentId, Guid cameraId, Guid requestId, CancellationToken ct = default)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var services = scope.ServiceProvider;
|
|
var access = services.GetRequiredService<ResourceAccess>();
|
|
var subscriptions = services.GetRequiredService<LiveSubscriptions>();
|
|
var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access,
|
|
r => access.AgentAsync(r, agentId, ct), ct);
|
|
if (recipients.Count == 0) return false;
|
|
await _hubContext.Clients.Clients(recipients).SendAsync("ManualSnapshotRequested", cameraId, requestId, ct);
|
|
_logger.LogInformation("Requested manual snapshot {RequestId} from agent {AgentId} for camera {CameraId}",
|
|
requestId, agentId, cameraId);
|
|
return true;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
|
|
{
|
|
_logger.LogInformation("Broadcasting full config reload to all agents");
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var services = scope.ServiceProvider;
|
|
var access = services.GetRequiredService<ResourceAccess>();
|
|
var subscriptions = services.GetRequiredService<LiveSubscriptions>();
|
|
await _hubContext.Clients.Clients(await subscriptions.AuthorizedAsync("config", "all", access, r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("ConfigReload", ct);
|
|
}
|
|
}
|