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

127 lines
5.9 KiB
C#
Raw Normal View History

using System.Text.Json;
using Heimdall.Application.DTOs;
using Heimdall.Application.Metrics;
namespace Heimdall.Agent.Services;
/// <summary>
/// Holds the camera assignments the agent must capture. The Central is the
/// source of truth: cameras are shipped as flat <c>camera.&lt;id&gt;.name|rtsp|sub_rtsp|enabled</c>
/// keys through the settings pipeline as one complete, versioned snapshot.
/// A local list from <c>AgentOptions.Cameras</c> serves as a fallback until
/// the first Central config is received.
/// </summary>
public sealed class CameraConfigStore
{
private sealed record CameraSnapshot(IReadOnlyDictionary<Guid, AgentCameraConfig> Cameras, string Version);
private CameraSnapshot? _central;
private int _centralConfigurationReceived;
private readonly object _updateGate = new();
private IReadOnlyList<AgentCameraConfig> _localFallback = [];
/// <summary>Raised whenever the effective camera list may have changed.</summary>
public event EventHandler? Changed;
/// <summary>Sets the local fallback list (used until Central config arrives).</summary>
public void SetLocalFallback(IReadOnlyList<AgentCameraConfig> cameras)
{
_localFallback = cameras;
RaiseChanged();
}
/// <summary>
/// Legacy single-key setter for local callers. Remote updates must use ReplaceCentral.
/// </summary>
public void ApplyCameraSetting(string key, string value)
{
// camera.<id>.<field>
var parts = key.Split('.', 3);
if (!key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
return;
if (parts.Length != 3 || !Guid.TryParse(parts[1], out var cameraId))
return;
lock (_updateGate)
{
var previous = _central?.Cameras ?? new Dictionary<Guid, AgentCameraConfig>();
var next = new Dictionary<Guid, AgentCameraConfig>(previous);
next[cameraId] = ApplyField(next.GetValueOrDefault(cameraId) ??
new AgentCameraConfig(cameraId, string.Empty, string.Empty, null, true), parts[2], value);
Volatile.Write(ref _central, new CameraSnapshot(next, string.Empty));
}
RaiseChanged();
}
/// <summary>
/// Marks the Central config as received; the local fallback is no longer
/// used, even if the Central list is empty.
/// </summary>
public void MarkCentralReceived()
{
var wasUninitialized = Interlocked.CompareExchange(ref _central,
new CameraSnapshot(new Dictionary<Guid, AgentCameraConfig>(), string.Empty), null) is null;
Volatile.Write(ref _centralConfigurationReceived, 1);
HeimdallMetrics.SetCentralConfigurationReceived(true);
if (wasUninitialized)
RaiseChanged();
}
/// <summary>Atomically replace the authoritative snapshot, including removals.</summary>
public void ReplaceCentral(IReadOnlyDictionary<string, string> settings, string? expectedVersion = null)
{
var version = CameraConfigVersion.Compute(settings);
if (expectedVersion is not null && !string.Equals(expectedVersion, version, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Camera configuration version mismatch", nameof(expectedVersion));
var replacement = new Dictionary<Guid, AgentCameraConfig>();
foreach (var setting in settings.Where(s => s.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)))
{
var parts = setting.Key.Split('.', 3);
if (parts.Length != 3 || !Guid.TryParse(parts[1], out var id))
throw new ArgumentException("Invalid camera setting key", nameof(settings));
replacement[id] = ApplyField(replacement.GetValueOrDefault(id) ??
new AgentCameraConfig(id, string.Empty, string.Empty, null, true), parts[2], setting.Value);
}
lock (_updateGate)
Volatile.Write(ref _central, new CameraSnapshot(replacement, version));
Volatile.Write(ref _centralConfigurationReceived, 1);
HeimdallMetrics.SetCentralConfigurationReceived(true);
RaiseChanged();
}
/// <summary>Effective camera assignments: Central list, or local fallback before that.</summary>
public IReadOnlyList<AgentCameraConfig> Cameras =>
Volatile.Read(ref _central)?.Cameras.Values.ToArray() ?? _localFallback;
/// <summary>Whether a valid full snapshot has been accepted from Central.</summary>
public bool HasCentralConfiguration => Volatile.Read(ref _centralConfigurationReceived) != 0;
public string? CurrentVersion => Volatile.Read(ref _central)?.Version;
private static AgentCameraConfig ApplyField(AgentCameraConfig existing, string field, string value) => field switch
{
"name" => existing with { Name = value },
"rtsp" => existing with { RtspUrl = value },
"sub_rtsp" => existing with { SubRtspUrl = value },
"enabled" => existing with { Enabled = ParseBool(value) },
2026-11-04 22:18:00 +01:00
"recording_enabled" => existing with { RecordingEnabled = ParseBool(value) },
"event_recording_enabled" => existing with { EventRecordingEnabled = ParseBool(value) },
"profile" => existing with { DetectionProfile = ParseProfile(value) },
_ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field))
};
private static DetectionProfileDto ParseProfile(string value)
{
var profile = JsonSerializer.Deserialize<DetectionProfileDto>(value) ?? throw new ArgumentException("Empty detection profile");
profile.Validate();
return profile;
}
private static bool ParseBool(string value) => value switch
{
"1" => true,
"0" => false,
_ when bool.TryParse(value, out var parsed) => parsed,
_ => throw new ArgumentException("Invalid camera enabled value", nameof(value))
};
private void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);
}