using System.Net.Http.Json;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
using Heimdall.Domain.Enums;
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 const int CameraConfigAckMaxAttempts = 3;
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly ILogger _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly DiscoveryScanTrigger _scanTrigger;
private readonly AgentCredentialStore _credentialStore;
private readonly RuntimeLogLevel _runtimeLogLevel;
private readonly CameraConfigStore _cameraStore;
private readonly CameraStreamService _streams;
private readonly IDetectionReporter _detectionReporter;
private readonly AgentUpdateService _updateService;
private readonly DockerUpdateService _dockerUpdateService;
private readonly ContainerInfoProvider _containerInfo;
private HubConnection? _connection;
private readonly SemaphoreSlim _reloadLock = new(1, 1);
///
/// 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.
///
private static readonly HashSet RestartRequiredPrefixes =
new(StringComparer.OrdinalIgnoreCase)
{
"ai.detection.",
"detection.",
"model.",
"ffmpeg.",
"yolo.",
};
public ConfigReceiverService(
AgentState state,
IOptions options,
ILogger logger,
IHttpClientFactory httpClientFactory,
DiscoveryScanTrigger scanTrigger,
AgentCredentialStore credentialStore,
RuntimeLogLevel runtimeLogLevel,
CameraConfigStore cameraStore,
CameraStreamService streams,
IDetectionReporter detectionReporter,
AgentUpdateService updateService,
DockerUpdateService dockerUpdateService,
ContainerInfoProvider containerInfo)
{
_state = state;
_options = options.Value;
_logger = logger;
_httpClientFactory = httpClientFactory;
_scanTrigger = scanTrigger;
_credentialStore = credentialStore;
_runtimeLogLevel = runtimeLogLevel;
_cameraStore = cameraStore;
_streams = streams;
_detectionReporter = detectionReporter;
_updateService = updateService;
_dockerUpdateService = dockerUpdateService;
_containerInfo = containerInfo;
}
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());
_connection.On("ManualSnapshotRequested", async (cameraId, requestId) =>
{
if (requestId == Guid.Empty) return;
try
{
if (!_cameraStore.Cameras.Any(c => c.CameraId == cameraId && c.Enabled))
{
await ReportSnapshotFailureAsync(cameraId, requestId, "camera_unavailable", stoppingToken);
return;
}
var snapshot = await _streams.CaptureNextFrameAsync(cameraId, stoppingToken).ConfigureAwait(false);
if (snapshot is null)
{
_logger.LogWarning("Manual snapshot request {RequestId} has no active frame for camera {CameraId}", requestId, cameraId);
await ReportSnapshotFailureAsync(cameraId, requestId, "no_frame", stoppingToken);
return;
}
if (!await _detectionReporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
occurredAt: snapshot.TimestampUtc, snapshotJpeg: snapshot.JpegData,
eventId: requestId, ct: stoppingToken).ConfigureAwait(false))
{
_logger.LogWarning("Manual snapshot request {RequestId} could not be queued", requestId);
await ReportSnapshotFailureAsync(cameraId, requestId, "queue_failed", stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
catch (Exception ex)
{
_logger.LogWarning(ex, "Manual snapshot request {RequestId} failed", requestId);
try { await ReportSnapshotFailureAsync(cameraId, requestId, "agent_error", stoppingToken); }
catch (Exception reportError)
{
_logger.LogWarning(reportError, "Could not report manual snapshot failure {RequestId}", requestId);
}
}
});
_connection.On("AgentUpdateRequested", () => _containerInfo.Collect().IsContainer
? _dockerUpdateService.RequestUpdateAsync(stoppingToken)
: _updateService.RequestUpdateAsync(stoppingToken));
// Listen for setting changes
_connection.On("SettingChanged", async (key, value) =>
{
// Keys may identify secret settings; never log their values.
_logger.LogInformation("Config update received: {Key}", key);
if (key == "config.invalidated" || key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
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);
}
}
}
private async Task ReportSnapshotFailureAsync(Guid cameraId, Guid requestId, string code, CancellationToken ct)
{
using var http = _httpClientFactory.CreateClient("Central");
http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/cameras/{cameraId:D}/snapshot/{requestId:D}/failure";
using var response = await http.PutAsJsonAsync(url, new { code }, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
}
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)
{
// Remote camera keys are applied only through an authoritative versioned
// full snapshot. This branch remains for local callers.
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(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;
}
}
///
/// 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).
///
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}";
using 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>(ct);
if (config is null)
{
_logger.LogWarning("Full configuration response was empty");
return;
}
var version = response.Headers.TryGetValues("X-Camera-Config-Version", out var values)
? values.SingleOrDefault()
: null;
if (string.IsNullOrWhiteSpace(version))
{
_logger.LogWarning("Full camera configuration has no version header");
return;
}
// Validate and publish all camera fields together before applying
// independent agent settings. An invalid camera snapshot leaves the
// previously active assignments intact.
_cameraStore.ReplaceCentral(config, version);
_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);
// The Central camera list is authoritative once the full config
// arrives — even if it is empty, drop the local fallback.
_cameraStore.MarkCentralReceived();
var acknowledged = await AcknowledgeCameraConfigurationAsync(http, version, ct).ConfigureAwait(false);
if (!acknowledged)
_logger.LogWarning("Camera configuration ACK could not be persisted after {Attempts} attempts",
CameraConfigAckMaxAttempts);
}
catch (Exception ex)
{
_logger.LogWarning("Failed to fetch full configuration (error type {ErrorType})", ex.GetType().Name);
}
finally { _reloadLock.Release(); }
}
private async Task AcknowledgeCameraConfigurationAsync(HttpClient http, string version, CancellationToken ct)
{
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack";
for (var attempt = 1; attempt <= CameraConfigAckMaxAttempts; attempt++)
{
try
{
using var response = await http.PostAsJsonAsync(url, new { version }, ct).ConfigureAwait(false);
if (response.IsSuccessStatusCode) return true;
_logger.LogWarning("Camera configuration ACK attempt {Attempt} was rejected with HTTP {StatusCode}",
attempt, (int)response.StatusCode);
if (response.StatusCode is not (System.Net.HttpStatusCode.RequestTimeout or
System.Net.HttpStatusCode.TooManyRequests) && (int)response.StatusCode < 500)
return false;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
{
_logger.LogWarning("Camera configuration ACK attempt {Attempt} failed ({ErrorType})",
attempt, ex.GetType().Name);
}
if (attempt < CameraConfigAckMaxAttempts)
await Task.Delay(TimeSpan.FromMilliseconds(250 * attempt), ct).ConfigureAwait(false);
}
return false;
}
}
///
/// 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);
}
}