Files
Heimdall/src/Heimdall.Web/Hubs/ConfigHub.cs
T

117 lines
5.4 KiB
C#

using Heimdall.Api.Security;
using Heimdall.Application.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
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();
_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();
_logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
}
/// <summary>
/// Broadcasts config changes to connected agents via SignalR.
/// Injected as a scoped service; the HubContext is a singleton so broadcasting
/// works safely across all connected clients.
/// </summary>
public class ConfigBroadcastService : IConfigBroadcastService
{
private readonly IHubContext<ConfigHub> _hubContext;
private readonly ILogger<ConfigBroadcastService> _logger;
private readonly ResourceAccess _access;
private readonly LiveSubscriptions _subscriptions;
private readonly IApplicationDbContext _db;
public ConfigBroadcastService(IHubContext<ConfigHub> hubContext, ILogger<ConfigBroadcastService> logger, IApplicationDbContext db, ResourceAccess access, LiveSubscriptions subscriptions)
{
_db = db;
_access = access;
_subscriptions = subscriptions;
_hubContext = hubContext;
_logger = logger;
}
/// <inheritdoc />
public async Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default)
{
if (!await _db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return;
_logger.LogDebug("Broadcasting global setting change: {Key}", key);
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)
{
// 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;
}
if (!await _db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return;
_logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key}", agentId, key);
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("config", $"agent_{agentId}", _access, r => _access.AgentAsync(r, agentId, ct), ct)).SendAsync("SettingChanged", key, value, ct);
}
/// <inheritdoc />
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
{
_logger.LogInformation("Broadcasting full config reload to all agents");
await _hubContext.Clients.Clients(await _subscriptions.AuthorizedAsync("config", "all", _access, r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("ConfigReload", ct);
}
}