Files
Heimdall/src/Heimdall.Agent/Services/ConfigReceiverService.cs
T

326 lines
12 KiB
C#

using System.Net.Http.Json;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>
/// 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.
/// </summary>
public sealed class ConfigReceiverService : BackgroundService
{
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly ILogger<ConfigReceiverService> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly DiscoveryScanTrigger _scanTrigger;
private readonly AgentCredentialStore _credentialStore;
private readonly RuntimeLogLevel _runtimeLogLevel;
private readonly CameraConfigStore _cameraStore;
private HubConnection? _connection;
private readonly SemaphoreSlim _reloadLock = new(1, 1);
/// <summary>
/// Settings that are known but cannot be applied without an agent restart
/// (they are read once at startup by services that do not support hot
/// reload). They are logged explicitly so operators know why the change
/// has no immediate effect.
/// </summary>
private static readonly HashSet<string> RestartRequiredPrefixes =
new(StringComparer.OrdinalIgnoreCase)
{
"ai.detection.",
"detection.",
"model.",
"ffmpeg.",
"yolo.",
};
public ConfigReceiverService(
AgentState state,
IOptions<AgentOptions> options,
ILogger<ConfigReceiverService> logger,
IHttpClientFactory httpClientFactory,
DiscoveryScanTrigger scanTrigger,
AgentCredentialStore credentialStore,
RuntimeLogLevel runtimeLogLevel,
CameraConfigStore cameraStore)
{
_state = state;
_options = options.Value;
_logger = logger;
_httpClientFactory = httpClientFactory;
_scanTrigger = scanTrigger;
_credentialStore = credentialStore;
_runtimeLogLevel = runtimeLogLevel;
_cameraStore = cameraStore;
}
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();
_connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger());
// Listen for setting changes
_connection.On<string, string>("SettingChanged", async (key, value) =>
{
// Keys may identify secret settings; never log their values.
_logger.LogInformation("Config update received: {Key}", key);
if (key == "config.invalidated") await FetchFullConfigAsync(stoppingToken);
else ApplySetting(key, value);
});
// Listen for full reload signal
_connection.On("ConfigReload", async () =>
{
_logger.LogInformation("Full config reload requested, fetching from API...");
await FetchFullConfigAsync(stoppingToken);
});
// 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);
await FetchFullConfigAsync(stoppingToken);
}
catch (Exception ex)
{
_logger.LogWarning("Failed to rejoin agent group after reconnect (error type {ErrorType})", ex.GetType().Name);
}
};
// Retry loop for initial connection (auto-reconnect handles the rest)
while (!stoppingToken.IsCancellationRequested)
{
try
{
await _connection.StartAsync(stoppingToken);
_logger.LogInformation("Connected to config hub");
// 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
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
await FetchFullConfigAsync(stoppingToken);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
_logger.LogWarning("Config hub connection failed, retrying in 15s... (error type {ErrorType})", ex.GetType().Name);
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)
{
// Camera assignments are applied live: the capture pipeline resyncs
// on every store change (start new streams, stop removed ones).
if (key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
{
_cameraStore.ApplyCameraSetting(key, value);
return;
}
// Apply known settings locally (live, no restart required)
switch (key)
{
case "heartbeat.interval.seconds":
if (int.TryParse(value, out var interval) && interval >= 5 && interval <= 300)
{
_state.HeartbeatIntervalSeconds = interval;
_logger.LogInformation("Heartbeat interval updated to {Interval}s (applied live)", interval);
}
else
{
_logger.LogWarning("Ignored invalid heartbeat interval");
}
break;
case "log.level":
if (Enum.TryParse<LogLevel>(value, ignoreCase: true, out var level))
{
_runtimeLogLevel.Set(level);
_logger.LogInformation("Log level updated to {Level} (applied live)", level);
}
else
{
_logger.LogWarning("Ignored invalid log level");
}
break;
case "discovery.scan.requested":
_logger.LogInformation("Camera discovery scan requested by Central");
_scanTrigger.Trigger();
break;
case "discovery.credentials":
ApplyCredentialPool(value);
break;
case "autoUpdateEnabled":
if (bool.TryParse(value, out var autoUpdate))
{
_options.AutoUpdateEnabled = autoUpdate;
_logger.LogInformation("Auto-update {Status} by Central config",
autoUpdate ? "enabled" : "disabled");
}
else
{
_logger.LogWarning("Ignored invalid autoUpdateEnabled value");
}
break;
default:
if (RestartRequiredPrefixes.Any(p => key.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
{
_logger.LogWarning(
"Setting {Key} requires an agent restart to take effect (not applied live)",
key);
}
else
{
_logger.LogDebug("Unknown setting {Key} (stored for future use)", key);
}
break;
}
}
/// <summary>
/// Decrypt the site's camera credential pool shipped by the Central and
/// store it for the discovery scanner. Uses the agent's plaintext API key
/// (only the agent can open the envelope).
/// </summary>
private void ApplyCredentialPool(string envelope)
{
try
{
if (string.IsNullOrEmpty(_state.ApiKey))
{
_logger.LogWarning("Credential pool received but no API key available — cannot decrypt");
return;
}
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(_state.ApiKey);
var pool = AgentCredentialEnvelope.Decrypt(envelope, key);
_credentialStore.Set(pool);
_logger.LogInformation("Camera credential pool updated: {Count} pair(s)", pool.Count);
}
catch (Exception ex)
{
_logger.LogWarning("Failed to decrypt camera credential pool (kept previous pool) (error type {ErrorType})", ex.GetType().Name);
}
}
private async Task FetchFullConfigAsync(CancellationToken ct)
{
await _reloadLock.WaitAsync(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.LogWarning("Failed to fetch full configuration: {StatusCode}", response.StatusCode);
return;
}
var config = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>(ct);
if (config is null)
{
_logger.LogWarning("Full configuration response was empty");
return;
}
_logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count);
// Apply every key through the same pipeline as live SettingChanged
// events — heartbeat interval, log level, credentials, restart-required
// documentation, everything.
foreach (var kvp in config.Where(kvp => !kvp.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)))
ApplySetting(kvp.Key, kvp.Value);
_cameraStore.ReplaceCentral(config);
// The Central camera list is authoritative once the full config
// arrives — even if it is empty, drop the local fallback.
_cameraStore.MarkCentralReceived();
}
catch (Exception ex)
{
_logger.LogWarning("Failed to fetch full configuration (error type {ErrorType})", ex.GetType().Name);
}
finally { _reloadLock.Release(); }
}
}
/// <summary>
/// Retry policy for SignalR reconnection with specific delays.
/// </summary>
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);
}
}