using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
///
/// Connects to the Central SignalR ConfigHub to receive real-time configuration updates.
/// When a setting changes, applies it locally and logs the change.
/// Service will auto-reconnect on connection loss.
///
public sealed class ConfigReceiverService : BackgroundService
{
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly ILogger _logger;
private readonly IHttpClientFactory _httpClientFactory;
private HubConnection? _connection;
public ConfigReceiverService(
AgentState state,
IOptions options,
ILogger logger,
IHttpClientFactory httpClientFactory)
{
_state = state;
_options = options.Value;
_logger = logger;
_httpClientFactory = httpClientFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Wait until the agent is registered (has an AgentId)
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
if (stoppingToken.IsCancellationRequested) return;
var hubUrl = $"{_options.CentralUrl.TrimEnd('/')}/hubs/config";
_connection = new HubConnectionBuilder()
.WithUrl(hubUrl, options =>
{
options.AccessTokenProvider = () => Task.FromResult(_state.ApiKey);
})
.WithAutomaticReconnect(new RetryDelayed(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30)))
.Build();
// Listen for setting changes
_connection.On("SettingChanged", (key, value) =>
{
_logger.LogInformation("Config update received: {Key} = {Value}", key, value);
ApplySetting(key, value);
});
// Listen for full reload signal
_connection.On("ConfigReload", () =>
{
_logger.LogInformation("Full config reload requested, fetching from API...");
_ = FetchFullConfigAsync(CancellationToken.None);
});
// Reconnection events
_connection.Reconnecting += _ =>
{
_logger.LogWarning("Config hub connection lost, reconnecting...");
return Task.CompletedTask;
};
_connection.Reconnected += async _ =>
{
_logger.LogInformation("Config hub reconnected, rejoining agent group...");
try
{
await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to rejoin agent group after reconnect");
}
};
// Retry loop for initial connection (auto-reconnect handles the rest)
while (!stoppingToken.IsCancellationRequested)
{
try
{
await _connection.StartAsync(stoppingToken);
_logger.LogInformation("Connected to config hub at {HubUrl}", hubUrl);
// Join our personal config channel
await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
// Fetch initial full config
await FetchFullConfigAsync(stoppingToken);
// Keep service alive until cancellation — auto-reconnect handles reconnection
await Task.Delay(Timeout.Infinite, stoppingToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Config hub connection failed, retrying in 15s...");
await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
}
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
if (_connection is not null)
{
try { await _connection.DisposeAsync(); }
catch { /* best effort */ }
}
await base.StopAsync(cancellationToken);
}
private void ApplySetting(string key, string value)
{
// Apply known settings locally
switch (key)
{
case "heartbeat.interval.seconds":
if (int.TryParse(value, out var interval) && interval >= 5)
{
// The heartbeat interval will be read from options on next heartbeat
_logger.LogInformation("Heartbeat interval updated to {Interval}s (applied on next restart)", interval);
}
break;
case "log.level":
_logger.LogInformation("Log level update received: {Level} (applied on next restart)", value);
break;
default:
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
break;
}
}
private async Task FetchFullConfigAsync(CancellationToken ct)
{
try
{
using var http = _httpClientFactory.CreateClient("Central");
http.Timeout = TimeSpan.FromSeconds(10);
// Central's ApiKey scheme reads X-API-Key (never Bearer for agent keys)
http.DefaultRequestHeaders.Remove("X-API-Key");
http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
var response = await http.GetAsync(url, ct);
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Full configuration fetched successfully");
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to fetch full configuration");
}
}
}
///
/// Retry policy for SignalR reconnection with specific delays.
///
internal sealed class RetryDelayed : IRetryPolicy
{
private readonly TimeSpan[] _delays;
public RetryDelayed(params TimeSpan[] delays) => _delays = delays;
public TimeSpan? NextRetryDelay(RetryContext context)
{
if (context.PreviousRetryCount >= 0 && context.PreviousRetryCount < _delays.Length)
return _delays[context.PreviousRetryCount];
// After exhausting specified delays, retry every 60 seconds
return TimeSpan.FromSeconds(60);
}
}