2026-08-11 16:15:41 +02:00
|
|
|
using System.Net.Http.Json;
|
|
|
|
|
using Heimdall.Application.DTOs;
|
|
|
|
|
using Heimdall.Application.Security;
|
2026-10-23 07:20:47 +02:00
|
|
|
using Heimdall.Domain.Enums;
|
2026-07-18 18:58:20 +00:00
|
|
|
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;
|
2026-07-19 19:58:45 +00:00
|
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
2026-08-11 16:15:41 +02:00
|
|
|
private readonly DiscoveryScanTrigger _scanTrigger;
|
|
|
|
|
private readonly AgentCredentialStore _credentialStore;
|
2026-08-11 17:34:22 +02:00
|
|
|
private readonly RuntimeLogLevel _runtimeLogLevel;
|
2026-08-11 21:16:28 +02:00
|
|
|
private readonly CameraConfigStore _cameraStore;
|
2026-10-23 07:20:47 +02:00
|
|
|
private readonly CameraStreamService _streams;
|
|
|
|
|
private readonly IDetectionReporter _detectionReporter;
|
2026-10-21 09:20:07 +02:00
|
|
|
private readonly AgentUpdateService _updateService;
|
|
|
|
|
private readonly DockerUpdateService _dockerUpdateService;
|
|
|
|
|
private readonly ContainerInfoProvider _containerInfo;
|
2026-07-18 18:58:20 +00:00
|
|
|
private HubConnection? _connection;
|
2026-10-20 02:26:49 +02:00
|
|
|
private readonly SemaphoreSlim _reloadLock = new(1, 1);
|
2026-07-18 18:58:20 +00:00
|
|
|
|
2026-08-11 17:34:22 +02:00
|
|
|
/// <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.",
|
|
|
|
|
};
|
|
|
|
|
|
2026-07-18 18:58:20 +00:00
|
|
|
public ConfigReceiverService(
|
|
|
|
|
AgentState state,
|
|
|
|
|
IOptions<AgentOptions> options,
|
2026-07-19 19:58:45 +00:00
|
|
|
ILogger<ConfigReceiverService> logger,
|
2026-08-11 16:15:41 +02:00
|
|
|
IHttpClientFactory httpClientFactory,
|
|
|
|
|
DiscoveryScanTrigger scanTrigger,
|
2026-08-11 17:34:22 +02:00
|
|
|
AgentCredentialStore credentialStore,
|
2026-08-11 21:16:28 +02:00
|
|
|
RuntimeLogLevel runtimeLogLevel,
|
2026-10-21 09:20:07 +02:00
|
|
|
CameraConfigStore cameraStore,
|
2026-10-23 07:20:47 +02:00
|
|
|
CameraStreamService streams,
|
|
|
|
|
IDetectionReporter detectionReporter,
|
2026-10-21 09:20:07 +02:00
|
|
|
AgentUpdateService updateService,
|
|
|
|
|
DockerUpdateService dockerUpdateService,
|
|
|
|
|
ContainerInfoProvider containerInfo)
|
2026-07-18 18:58:20 +00:00
|
|
|
{
|
|
|
|
|
_state = state;
|
|
|
|
|
_options = options.Value;
|
|
|
|
|
_logger = logger;
|
2026-07-19 19:58:45 +00:00
|
|
|
_httpClientFactory = httpClientFactory;
|
2026-08-11 16:15:41 +02:00
|
|
|
_scanTrigger = scanTrigger;
|
|
|
|
|
_credentialStore = credentialStore;
|
2026-08-11 17:34:22 +02:00
|
|
|
_runtimeLogLevel = runtimeLogLevel;
|
2026-08-11 21:16:28 +02:00
|
|
|
_cameraStore = cameraStore;
|
2026-10-23 07:20:47 +02:00
|
|
|
_streams = streams;
|
|
|
|
|
_detectionReporter = detectionReporter;
|
2026-10-21 09:20:07 +02:00
|
|
|
_updateService = updateService;
|
|
|
|
|
_dockerUpdateService = dockerUpdateService;
|
|
|
|
|
_containerInfo = containerInfo;
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
|
2026-10-20 07:16:44 +02:00
|
|
|
_connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger());
|
2026-10-23 07:20:47 +02:00
|
|
|
_connection.On<Guid, Guid>("ManualSnapshotRequested", async (cameraId, requestId) =>
|
|
|
|
|
{
|
2026-10-23 07:30:58 +02:00
|
|
|
if (requestId == Guid.Empty) return;
|
2026-10-23 07:20:47 +02:00
|
|
|
try
|
|
|
|
|
{
|
2026-10-23 07:30:58 +02:00
|
|
|
if (!_cameraStore.Cameras.Any(c => c.CameraId == cameraId && c.Enabled))
|
|
|
|
|
{
|
|
|
|
|
await ReportSnapshotFailureAsync(cameraId, requestId, "camera_unavailable", stoppingToken);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-10-23 07:20:47 +02:00
|
|
|
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);
|
2026-10-23 07:30:58 +02:00
|
|
|
await ReportSnapshotFailureAsync(cameraId, requestId, "no_frame", stoppingToken);
|
2026-10-23 07:20:47 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (!await _detectionReporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
|
|
|
|
|
occurredAt: snapshot.TimestampUtc, snapshotJpeg: snapshot.JpegData,
|
|
|
|
|
eventId: requestId, ct: stoppingToken).ConfigureAwait(false))
|
2026-10-23 07:30:58 +02:00
|
|
|
{
|
2026-10-23 07:20:47 +02:00
|
|
|
_logger.LogWarning("Manual snapshot request {RequestId} could not be queued", requestId);
|
2026-10-23 07:30:58 +02:00
|
|
|
await ReportSnapshotFailureAsync(cameraId, requestId, "queue_failed", stoppingToken);
|
|
|
|
|
}
|
2026-10-23 07:20:47 +02:00
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(ex, "Manual snapshot request {RequestId} failed", requestId);
|
2026-10-23 07:30:58 +02:00
|
|
|
try { await ReportSnapshotFailureAsync(cameraId, requestId, "agent_error", stoppingToken); }
|
|
|
|
|
catch (Exception reportError)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(reportError, "Could not report manual snapshot failure {RequestId}", requestId);
|
|
|
|
|
}
|
2026-10-23 07:20:47 +02:00
|
|
|
}
|
|
|
|
|
});
|
2026-10-21 09:20:07 +02:00
|
|
|
_connection.On("AgentUpdateRequested", () => _containerInfo.Collect().IsContainer
|
|
|
|
|
? _dockerUpdateService.RequestUpdateAsync(stoppingToken)
|
|
|
|
|
: _updateService.RequestUpdateAsync(stoppingToken));
|
2026-10-20 07:16:44 +02:00
|
|
|
|
2026-07-18 18:58:20 +00:00
|
|
|
// Listen for setting changes
|
2026-10-20 02:26:49 +02:00
|
|
|
_connection.On<string, string>("SettingChanged", async (key, value) =>
|
2026-07-18 18:58:20 +00:00
|
|
|
{
|
2026-10-20 07:26:50 +02:00
|
|
|
// Keys may identify secret settings; never log their values.
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogInformation("Config update received: {Key}", key);
|
2026-10-23 07:30:58 +02:00
|
|
|
if (key == "config.invalidated" || key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
await FetchFullConfigAsync(stoppingToken);
|
2026-10-20 02:26:49 +02:00
|
|
|
else ApplySetting(key, value);
|
2026-07-18 18:58:20 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Listen for full reload signal
|
2026-10-20 02:26:49 +02:00
|
|
|
_connection.On("ConfigReload", async () =>
|
2026-07-18 18:58:20 +00:00
|
|
|
{
|
|
|
|
|
_logger.LogInformation("Full config reload requested, fetching from API...");
|
2026-10-20 02:26:49 +02:00
|
|
|
await FetchFullConfigAsync(stoppingToken);
|
2026-07-18 18:58:20 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 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);
|
2026-10-20 02:26:49 +02:00
|
|
|
await FetchFullConfigAsync(stoppingToken);
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("Failed to rejoin agent group after reconnect (error type {ErrorType})", ex.GetType().Name);
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Retry loop for initial connection (auto-reconnect handles the rest)
|
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await _connection.StartAsync(stoppingToken);
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogInformation("Connected to config hub");
|
2026-07-18 18:58:20 +00:00
|
|
|
|
|
|
|
|
// 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
|
2026-10-20 02:26:49 +02:00
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
|
|
|
|
|
await FetchFullConfigAsync(stoppingToken);
|
|
|
|
|
}
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("Config hub connection failed, retrying in 15s... (error type {ErrorType})", ex.GetType().Name);
|
2026-07-18 18:58:20 +00:00
|
|
|
await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 07:30:58 +02:00
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-18 18:58:20 +00:00
|
|
|
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)
|
|
|
|
|
{
|
2026-10-23 07:30:58 +02:00
|
|
|
// Remote camera keys are applied only through an authoritative versioned
|
|
|
|
|
// full snapshot. This branch remains for local callers.
|
2026-08-11 21:16:28 +02:00
|
|
|
if (key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
_cameraStore.ApplyCameraSetting(key, value);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-10 11:02:37 +02:00
|
|
|
// Apply known settings locally (live, no restart required)
|
2026-07-18 18:58:20 +00:00
|
|
|
switch (key)
|
|
|
|
|
{
|
|
|
|
|
case "heartbeat.interval.seconds":
|
2026-08-10 11:02:37 +02:00
|
|
|
if (int.TryParse(value, out var interval) && interval >= 5 && interval <= 300)
|
2026-07-18 18:58:20 +00:00
|
|
|
{
|
2026-08-10 11:02:37 +02:00
|
|
|
_state.HeartbeatIntervalSeconds = interval;
|
|
|
|
|
_logger.LogInformation("Heartbeat interval updated to {Interval}s (applied live)", interval);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("Ignored invalid heartbeat interval");
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case "log.level":
|
2026-08-11 17:34:22 +02:00
|
|
|
if (Enum.TryParse<LogLevel>(value, ignoreCase: true, out var level))
|
|
|
|
|
{
|
|
|
|
|
_runtimeLogLevel.Set(level);
|
|
|
|
|
_logger.LogInformation("Log level updated to {Level} (applied live)", level);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("Ignored invalid log level");
|
2026-08-11 17:34:22 +02:00
|
|
|
}
|
2026-07-18 18:58:20 +00:00
|
|
|
break;
|
2026-08-11 16:15:41 +02:00
|
|
|
case "discovery.scan.requested":
|
|
|
|
|
_logger.LogInformation("Camera discovery scan requested by Central");
|
|
|
|
|
_scanTrigger.Trigger();
|
|
|
|
|
break;
|
|
|
|
|
case "discovery.credentials":
|
|
|
|
|
ApplyCredentialPool(value);
|
|
|
|
|
break;
|
2026-10-26 11:38:24 +01:00
|
|
|
case "autoupdateenabled":
|
2026-08-27 18:56:57 +02:00
|
|
|
if (bool.TryParse(value, out var autoUpdate))
|
|
|
|
|
{
|
|
|
|
|
_options.AutoUpdateEnabled = autoUpdate;
|
|
|
|
|
_logger.LogInformation("Auto-update {Status} by Central config",
|
|
|
|
|
autoUpdate ? "enabled" : "disabled");
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("Ignored invalid autoUpdateEnabled value");
|
2026-08-27 18:56:57 +02:00
|
|
|
}
|
|
|
|
|
break;
|
2026-07-18 18:58:20 +00:00
|
|
|
default:
|
2026-08-11 17:34:22 +02:00
|
|
|
if (RestartRequiredPrefixes.Any(p => key.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(
|
2026-10-20 07:16:44 +02:00
|
|
|
"Setting {Key} requires an agent restart to take effect (not applied live)",
|
|
|
|
|
key);
|
2026-08-11 17:34:22 +02:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogDebug("Unknown setting {Key} (stored for future use)", key);
|
2026-08-11 17:34:22 +02:00
|
|
|
}
|
2026-07-18 18:58:20 +00:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
/// <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)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("Failed to decrypt camera credential pool (kept previous pool) (error type {ErrorType})", ex.GetType().Name);
|
2026-08-11 16:15:41 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-18 18:58:20 +00:00
|
|
|
private async Task FetchFullConfigAsync(CancellationToken ct)
|
|
|
|
|
{
|
2026-10-20 02:26:49 +02:00
|
|
|
await _reloadLock.WaitAsync(ct);
|
2026-07-18 18:58:20 +00:00
|
|
|
try
|
|
|
|
|
{
|
2026-07-19 19:58:45 +00:00
|
|
|
using var http = _httpClientFactory.CreateClient("Central");
|
|
|
|
|
http.Timeout = TimeSpan.FromSeconds(10);
|
2026-08-10 10:26:31 +02:00
|
|
|
// 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);
|
2026-07-18 18:58:20 +00:00
|
|
|
|
|
|
|
|
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
|
2026-10-23 07:30:58 +02:00
|
|
|
using var response = await http.GetAsync(url, ct);
|
2026-07-18 18:58:20 +00:00
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
if (!response.IsSuccessStatusCode)
|
2026-07-18 18:58:20 +00:00
|
|
|
{
|
2026-08-11 16:15:41 +02:00
|
|
|
_logger.LogWarning("Failed to fetch full configuration: {StatusCode}", response.StatusCode);
|
|
|
|
|
return;
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
2026-08-11 16:15:41 +02:00
|
|
|
|
|
|
|
|
var config = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>(ct);
|
|
|
|
|
if (config is null)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Full configuration response was empty");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 07:30:58 +02:00
|
|
|
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);
|
|
|
|
|
|
2026-08-11 16:15:41 +02:00
|
|
|
_logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count);
|
|
|
|
|
|
2026-08-11 17:34:22 +02:00
|
|
|
// Apply every key through the same pipeline as live SettingChanged
|
|
|
|
|
// events — heartbeat interval, log level, credentials, restart-required
|
|
|
|
|
// documentation, everything.
|
2026-10-20 02:26:49 +02:00
|
|
|
foreach (var kvp in config.Where(kvp => !kvp.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)))
|
2026-08-11 17:34:22 +02:00
|
|
|
ApplySetting(kvp.Key, kvp.Value);
|
2026-08-11 21:16:28 +02:00
|
|
|
// The Central camera list is authoritative once the full config
|
|
|
|
|
// arrives — even if it is empty, drop the local fallback.
|
|
|
|
|
_cameraStore.MarkCentralReceived();
|
2026-10-23 07:30:58 +02:00
|
|
|
|
|
|
|
|
using var ack = await http.PostAsJsonAsync(
|
|
|
|
|
$"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack",
|
|
|
|
|
new { version }, ct).ConfigureAwait(false);
|
|
|
|
|
if (!ack.IsSuccessStatusCode)
|
|
|
|
|
_logger.LogWarning("Camera configuration ACK was rejected: {StatusCode}", ack.StatusCode);
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-10-20 07:16:44 +02:00
|
|
|
_logger.LogWarning("Failed to fetch full configuration (error type {ErrorType})", ex.GetType().Name);
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
2026-10-20 02:26:49 +02:00
|
|
|
finally { _reloadLock.Release(); }
|
2026-07-18 18:58:20 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <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)
|
|
|
|
|
{
|
2026-07-23 19:19:05 +00:00
|
|
|
if (context.PreviousRetryCount >= 0 && context.PreviousRetryCount < _delays.Length)
|
2026-07-18 18:58:20 +00:00
|
|
|
return _delays[context.PreviousRetryCount];
|
|
|
|
|
|
|
|
|
|
// After exhausting specified delays, retry every 60 seconds
|
|
|
|
|
return TimeSpan.FromSeconds(60);
|
|
|
|
|
}
|
|
|
|
|
}
|